In this article, we will see how to validate a password using a regular expression.
Password validation is a common requirement in web applications. For example, an application may require a password to contain at least one letter, one number, and one special character, with the password length within a specified range.
The following JavaScript function validates a password that:
- Contains at least one letter
- Contains at least one number
- Contains at least one special character (
#,@,%, or$) - Has a length between 6 and 20 characters
JavaScript
function validatePassword(pwdelem, alertmsg) {
var passwordExpression =
/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[#@%$]).{6,20}$/;
if (passwordExpression.test(pwdelem.value)) {
return true;
} else {
alert(alertmsg);
pwdelem.focus();
return false;
}
}
The `pwdelem` parameter represents the password input element, while `alertmsg` contains the message to display when the password does not meet the required conditions.
The `pwdelem.focus()` statement is optional. It places the cursor back in the password field when validation fails.
Important Note
This JavaScript validation is performed on the client side and is useful for providing immediate feedback to the user. However, it should not be relied upon for security.
Password requirements must also be validated on the server side because client-side JavaScript can be bypassed.