Angular 2 regex error validation pattern

I am creating a form in angular that requires the name field to only contain alphanumeric characters and spaces. I use the pattern attribute for this:

<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 that 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 needs to match the regex, I still see the error message. Any ideas?

+3


source to share


2 answers


you can use

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

      



[A-Za-z\d_]

matches the same characters as \w

in JavaScript's native regex. Thus, the entire pattern matches one or more ASCII letters, numbers, underscores, hyphens, or spaces.

Note that angular binds the template by default, but it is preferable to keep the anchors in the template ^

and $

to make it compatible with any other frameworks.

+1


source


I guess the problem is that the regex syntax is not well 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 plunkr

+3


source







All Articles