1

I've implemented a pattern in angular 5 with the following code in the .ts file for password verification. This suppose to do - support minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character. See: Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

wcodePattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z0-9\d$@$-_!%*?&]{8,20}"; 

I see, when I entered a string in the password text box e.g. Niladri1! its working however, when I entered a string like Nopasss123!!, it shows User name not valid..

Below is the code for angular 5 html:

<div *ngIf="wcode.errors?.pattern">User name not valid.</div> 

I have also tested with the following and it takes string as Noladris which suppose to be invalid.

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@-_!])[A-Za-z0-9\d@-_!]{8,20}$

Anything I missed?

  • Did you take the solution from https://stackoverflow.com/a/21456918/3832970? I fixed some issues there just now. Add `$` to the end and remove one `$` inside the character class. Also, put `-` before the closing `]`. `^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-z0-9@$_!%*?&-]{8,20}$` should work, see [demo](https://regex101.com/r/9XmaFU/2). – Wiktor Stribiżew Sep 14 '18 at 10:42
  • @WiktorStribiżew I've added what I have taken as you suggested. Please check the question once again and let me know. – Niladri Banerjee - Uttarpara Sep 14 '18 at 11:00
  • Sure , that is because you did not escape the hyphen, and [`[@-_]+`](https://regex101.com/r/wtfOoz/1) matches all ASCII letters and more. – Wiktor Stribiżew Sep 14 '18 at 11:03

1 Answers1

1

You need to use

wcodePattern = '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-z0-9@$_!%*?&-]{8,20}$'

Or, since you are using it inside a RegExp constructor, here is a version for use there:

wcodePattern = '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$_!%*?&-]{8,20}$'

Note:

  • You must put - at the start/end of the character class to match a literal hyphen, or escape it inside
  • Backslashes in a string literal must be doubled, else they define escape sequences like \n, \t, etc.
  • $ must be added at the end of the pattern to "anchor" the match (i.e. match the end of the string to ensure the max char restriction).
  • [$@$] = [$@] - there is no need repeating the chars inside a character class.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563