1

I have a regex for validating a password which has to be at least 8 chars and must contain letter(upper and lower case) number and a special character from set ^ $ * . [ ] { } ( ) ? - " ! @ # % & / \ , > < ' : ; | _ ~ ` .

I face 2 problems, after adding the / to the reg exp its not recognized (other characters are still working OK. If I add the /] as well the expression no longer works (everything is invalid though the pattern seems to be ok in the browser debug mode).

The regex string

  static get PASSWORD_VALIDATION_REGEX(): string {
    return '(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])' +  // contains lowercase number uppercase
      '(?=.*[\-~\$@!%#<>\|\`\\\/\[;:=\+\{\}\.\(\)*^\?&\"\,\'])' + // special 
      '.{8,}'; // more than  allowed char
  }

I used the regexp as a form validator and as a match in function

    password: ['', {validators: [Validators.required,
      Validators.pattern(StringUtils.PASSWORD_VALIDATION_REGEX)
        ],
        updateOn: 'change'
      }
    ]
//....
value.match(StringUtils.PASSWORD_VALIDATION_REGEX)

Tried to use only (?=.*[\\]) for the special chars list, in that case I've received a console error Invalid regular expression: /^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[\]).{8,}$/: Unterminated character class

For '(?=.*[\]])' no console error but the following error is present in the form validation 'pattern'

actualValue: "AsasassasaX000[[][]"
requiredPattern: "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[]]).{8,}$"

The same value and pattern fails on https://regex101.com/

Thanks for your help / suggestions in advance!

Geraj
  • 40
  • 5

1 Answers1

2

You have overescaped your pattern and failed to escape the ] char correctly. In JavaScript regex, ] inside a character class must be escaped.

If you are confused with how to define escapes inside a string literal (and it is rather confusing indeed), you should use a regex literal. One thing to remember about the regex use with Validators.pattern is that the string pattern is anchored by the Angular framework by enclosing the whole pattern with ^ and $, so these anchors must be present when you define the pattern as a regex literal.

Use

static get PASSWORD_VALIDATION_REGEX(): string {
    return /^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[-~$@!%#<>|`\\\/[\];:=+{}.()*^?&",']).{8,}$/;
}

Note the \] that matches a ] char and \\ to match \ inside [...].

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563