1

Hi, Anyone can explain to me why regex expression in pattern property is not working

  <input type="password" pattern="(?=.*[a-zA-Z])(?=.*[0-9])" minlength="6" [class.is-invalid]="passwordForm.errors && passwordForm.touched" #passwordForm="ngModel" name="password"  required class="form-control" [(ngModel)]="password">

 but i run in typescript it work well
 var mediumRegex = new RegExp("(?=.*[a-zA-Z])(?=.*[0-9])");
    console.log(
      mediumRegex.test("123asA")
  );

--->true
  console.log(
    mediumRegex.test("")
);
--->false
  console.log(
    mediumRegex.test("aaaa")
--->false

); console.log(
  mediumRegex.test("1z")
);
--->true
1
  • Please provide a minimal reproducible example of your issue. Commented Jun 5, 2019 at 8:34

1 Answer 1

1

Add a consuming .* at the end because the HTML5 regex must match and consume the whole input string (due to the fact it is wrapped with ^(?: and )$ behind the scenes when compiling the RegExp object):

<input type="password" pattern="(?=.*[a-zA-Z])(?=.*[0-9]).*" minlength="6" [class.is-invalid]="passwordForm.errors && passwordForm.touched" #passwordForm="ngModel" name="password"  required class="form-control" [(ngModel)]="password">

The pattern="(?=.*[a-zA-Z])(?=.*[0-9]).*" pattern can be improved if you replace .* in the lookaheads with reverse character classes:

pattern="(?=[^a-zA-Z]*[a-zA-Z])(?=[^0-9]*[0-9]).*"

See the principle of contrast in password regex validation.

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

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.