2

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.

Community
  • 1
  • 1
pwborodich
  • 382
  • 6
  • 22

2 Answers2

1

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))
cchamberlain
  • 17,444
  • 7
  • 59
  • 72
  • this solution should work.. it's the maxlength that is not working. I'm able to enter more than 15 characters – gerl Jan 03 '17 at 16:47
0

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.

Soviut
  • 88,194
  • 49
  • 192
  • 260