I am trying to validate the password using regular expression. The password is getting updated if we have all the characters as alphabets. Where am i going wrong ? is the regular expression right ?
function validatePassword() { var newPassword = document.getElementById('changePasswordForm').newPassword.value; var minNumberofChars = 6; var maxNumberofChars = 16; var regularExpression = /^[a-zA-Z0-9!@#$%^&*]{6,16}$/; alert(newPassword); if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars){ return false; } if(!regularExpression.test(newPassword)) { alert("password should contain atleast one number and one special character"); return false; } }
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
Use positive lookahead assertions:
var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character. That's what the lookahead above is for.
(?=.*[0-9])
- Assert a string has at least one number;(?=.*[!@#$%^&*])
- Assert a string has at least one special character.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With