Reputation: 492
My Regex: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])
It accepts at least 1 lowercase letter, 1 uppercase letter, 1 number and 1 special character.
I want this to work for minimum 8 characters. Should not match if string length less than 8.
I have tried (^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])){8,}
this. But it still accepts lengths less than 8 Abc@123
.
Upvotes: 2
Views: 1471
Reputation: 626950
You appended the limiting quantifier to a capture group 1 (around the whole pattern) meaning you want to repeat the lookahead checks 8 or more times.
Either add one more lookahead:
/^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/
^^^^^^^^^
See the regex demo.
Alternatively, you may add .{8,}
at the end
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}/
^^^^^
See this regex demo.
And no need to repeat the $
character inside the character class ([$@$!%*?&]
-> [@$!%*?&]
), unless you meant something else.
The lookahead at the start variation may turn out preferable in cases when the string won't match due to its length.
console.log(/^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/.test("1sD$"))
console.log(/^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/.test("1sD$2sD$"))
Upvotes: 3
Reputation: 3233
Minimum 8 characters at least 1 Alphabet and 1 Number:
"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"
Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character:
"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$"
Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}"
Upvotes: 0