Reputation: 47
Having some problem with FormControl() Validators.pattern() with this regex expression for validate password with 1 char, 1 digit, min 8 chars, max 16 chars.
Tested passwords that pass the validators:
asdfqwer //that should not pass the validator
zxcvasdf //that should not pass the validator
asdfqwer2 //that's correct
Tested password that do not pass the validators:
programm //that's correct
Trying this pattern in server-side or using online regex test platforms there are no problems
// some code
password: new FormControl('',
[
Validators.minLength(8),
Validators.maxLength(16),
Validators.pattern('^$|^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$')
]),
// some code
Upvotes: 1
Views: 843
Reputation: 627600
You may use
Validators.pattern('(?:(?=[^A-Za-z]*[A-Za-z])(?=\\D*\\d)[A-Za-z\\d]{8,16})?')
Angular will enclose the string pattern with ^
and $
automatically, making it '^(?:(?=[^A-Za-z]*[A-Za-z])(?=\\D*\\d)[A-Za-z\\d]{8,16})?$'
.
Note the double backslashes: in a string literal, you must escape a backslash with another backslash to define a literal backslash, which is a regex escape char.
Since the whole pattern is enclosed with an optional non-capturing group, an empty string will also be matched with the pattern.
The (?=[^A-Za-z]*[A-Za-z])
and (?=\\D*\\d)
now have no .*
which is in line with the principle of contrast.
Upvotes: 1