pwborodich
pwborodich

Reputation: 382

Angular2 form validation check for number

I am having a problem verifing the the password entered in my angular 2 form contains at least one number in it. The other validators work its just this pattern one. the regex I am using I got from Regex: Check if string contains at least one digit

Password:

<div *ngIf="signUpForm.controls['password'].invalid && signUpForm.controls['password'].dirty">
      <small *ngIf="signUpForm.controls['password'].errors.minlength">
                            Please enter a minimum of 6 characters
                        </small>
      <small *ngIf="signUpForm.controls['password'].errors.maxlength">
                            Password cannot exceed 15 characters
                        </small>
      <small *ngIf="signUpForm.controls['password'].errors.pattern">
                            Must contain digits
                        </small> 
 </div>

inside my form I have the following validator and specifically the pattern I want is to check if the string entered contains a number

"password":["", [
               Validators.required,
               Validators.minLength(6),
               Validators.maxLength(15),
               Validators.pattern('/\d')
           ]
       ]

The errors.patters ngIf never goes away even if there are numbers in the field, not sure what I am doing wrong. My other pattern validators for other fields work.

Upvotes: 2

Views: 4435

Answers (2)

cchamberlain
cchamberlain

Reputation: 17956

How about Validators.pattern('\\d+')?

If I understand this correctly, you would need to provide a backslash (not forward slash) to escape the backslash.

Written as a regular expression literal this would look like /\d+/, but I don't think Angular 2 supports those.

UPDATE If that's not working then it must be either something with your setup or a bug in Angular 2. I don't use Angular 2 personally so hard to say but you can see the regex itself is fine:

const regex = new RegExp('\\d+', 'g')
console.info('hiwefwe883290awefoijwfe8382jfwef'.match(regex))

Upvotes: 1

Soviut
Soviut

Reputation: 91535

Your pattern \d will only work for a single digit. You need to add a quantifier.

\d+

That will match one or more digits but not a blank value.

Upvotes: 0

Related Questions