I'm trying to validate a password using the following regex in JavaScript:
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/
The validation requirements are:
Here is the password validation configuration I use:
password: {
type: "string",
required: "Password is required",
matches: {
regex:
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/,
message:
"Please include at least one uppercase letter, one lowercase letter, one number, and one special character.",
},
min: {
value: 8,
message: "Password must be at least 8 characters",
},
max: {
value: 20,
message: "Password must not exceed 20 characters",
},
}
However, this regex fails for the string ogJ((48HzpZI.
The string meets all the criteria:
(
, )
)Can anyone help identify why the regex doesn't pass this string?
I tried validating the password string ogJ((48HzpZI using my regex:
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/
I expected the validation to pass because the string meets the requirements:
(
, )
)What happened instead?
The validation failed, and the string did not pass. I’m not sure why the regex isn't matching the string, even though all the conditions seem to be fulfilled.
The last part of your regex ([A-Za-z\d@$!%*?&]+
) matches only the characters specified within it and there are no parentheses.
You should use .+
instead to match all the characters because the validation has already been done before.