4

I'm creating a form in angular that requires the name field only contain alphanumeric characters and spaces. To do this I use the pattern attribute:

<input type="text" class="form-control" placeholder="Name" name="Name" [(ngModel)]="name" required pattern="/^[a-z\d-_\s]+$/i" #nameField="ngModel">

and I have the following error message I want to show when the string does not match:

<div *ngIf="nameField.errors">
   <div [hidden]="!nameField.errors.pattern">
       <p class="has-error">
          Only spaces, letters, and numbers are allowed.
       </p>
   </div>
</div>

However, it seems that even when the string should match the regular expression, I can still see the error message. Any ideas?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Jesse Sliter
  • 233
  • 1
  • 4
  • 15

2 Answers2

9

I guess the issue here is that the syntax of regex not correctly formed:

 <form novalidate #f="ngForm" novalidate>
    <input type="text" 
    class="form-control" 
    placeholder="Name" name="Name" 
    [(ngModel)]="name" 
    required pattern="^[A-Z\\a-z\\d-_\\s]+$" 
    #nameField="ngModel" >
    <div>
      <div *ngIf="nameField.errors?.pattern">
        <p class="has-error">
          Only spaces, letters, and numbers are allowed.
        </p>
        hame: {{nameField.errors | json}}
     </div>
    </div>
  </form>

look at this plunkr

happyZZR1400
  • 2,387
  • 3
  • 25
  • 43
  • Thanks for the help. While your answer worked, The answer bellow you worked a little better for my specific case so I've marked it as the answer. – Jesse Sliter Jun 04 '17 at 20:30
2

You may use

pattern="^[\w\s-]+$"

The [A-Za-z\d_] matches the same chars as \w in JavaScript native regex. The whole pattern thus matches one or more ASCII letters, digits, underscores, hyphens or white spaces.

Note that angular anchors the pattern by default, but it is preferable to keep the anchors ^ and $ explicit in the pattern to make it compatible with any other frameworks.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Thanks for the concise answer. Exactly what I was looking for. – Jesse Sliter Jun 04 '17 at 20:30
  • can you please help me to solve this https://stackoverflow.com/questions/52091334/password-validation-is-not-working-in-angular-5 @WiktorStribizew – Zhu Aug 30 '18 at 08:37