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.

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

1 Comment

this solution should work.. it's the maxlength that is not working. I'm able to enter more than 15 characters
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.