Angular pattern validation with regex
70,964
Solution 1
You have multiple issues with your current regex:
- Your regex doesn't have a quantifier for character class
-
Validators.pattern
doesn't need delimiters but you threw one at beginning - You should double escape tokens.
What you need is this:
Validators.pattern('^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=\\D*\\d)[A-Za-z\\d!$%@#£€*?&]{8,}$');
See live demo here
Solution 2
You have to add the quantifier [A-Za-z\d!$%@#£€*?&]{8,}
to repeat the character class a minimum of 8 times and separate the assertions for an uppercase and lowercase character:
Validators.pattern('^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)[A-Za-z\\d!$%@#£€*?&]{8,}$')
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d!$%@#£€*?&]{8,}$
-
^
Assert position at the start of the string -
(?=.*[A-Z])
Positive lookahead to assert that what follows is an uppercase character -
(?=.*[a-z])
Positive lookahead to assert that what follows is an lowercase character -
(?=.*\d)
Positive lookahead to assert that what follows is a digit -
[A-Za-z\d!$%@#£€*?&]{8,}
Match any of the charachters in the character class 8 or more times -
$
Assert position at the end of the line
const strings = [
"A88888jf",
"Aa88888jf",
"Aa888jf",
"AAAAAAAAAAA",
"aaaaaaaaaaaaaa",
"2222222222222222",
"1sAdfe44",
"$#fd#######"
];
let pattern = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d!$%@#£€*?&]{8,}$/;
strings.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
});
Author by
Nicolas
Student Interactive multimedia design (IMD) at Thomas More, Belgium. Always trying to learn and improve. Curious person, open for a challenge.
Updated on August 08, 2022Comments
-
Nicolas almost 2 years
I need to make a password pattern validator
the password should have:
- 1 uppercase letter
- 1 lowercase letter
- A number
- A minimum length of 8.
I found this regex pattern:
Validators.pattern('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!$%@#£€*?&]')
however, the validator always claims my input is invalid
errors: pattern: actualValue: "Test1234" requiredPattern: "^/^(?=.*[A-Za-z])(?=.*d)[A-Za-zd!$%@#£€*?&]$"
according to https://regex101.com/r/AfAdKp/1 this value is supposed to be valid.
Edit: to clarify, Test1234 is supposed to work
-
Nicolas almost 6 yearsThis doesn't work
pattern:{requiredPattern: "^(?=.*[A-Z])(?=.*[a-z])(?=.*d)[A-Za-zd!$%@#£€*?&]{8,}$", actualValue: "Test1234"}
-
The fourth bird almost 6 yearsWhy should
Test1234
not match? -
Nicolas almost 6 yearsThat's the problem, it's supposed to match, but it gives me the error cause it doesn't.
-
The fourth bird almost 6 years@Nicolas Can you add the error to your question? Did you try it without the forward slash?