Validate a password in JavaScript
This post will discuss how to validate a password in JavaScript.
To validate a password in JavaScript, we can use different functions depending on the criteria or rules that we want to apply to the password. For example, we may want to check the length, the characters, the case, the numbers, or the symbols of the password. Here are some of the common functions:
1. Using a regular expression
A regular expression is a pattern of characters that can be used to match and test a string. We can define a regular expression that represents the rules for a valid password, and then use the RegExp.test() function to check if a given password matches the pattern. For example, if we want to validate a password that must contain at least one lowercase letter, one uppercase letter, one number, and one special character, and must be between 8 and 15 characters long, we can use this regular expression:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Define a regular expression for a valid password const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w]).{8,15}$/; // Define a function that takes a password and returns true if it is valid, false otherwise function validatePassword(password) { // Test the password against the regular expression return passwordRegex.test(password); } // Test the function on some examples console.log(validatePassword("Hello@123")); // true console.log(validatePassword("hello123")); // false console.log(validatePassword("Hello@")); // false |
Another way is to use the String.match() function, which is a built-in function that takes a regex as a parameter and returns an array of the matches or null if no match is found. We can use this function to check if a string contains the required characters for a valid password. For example, we can use this function to validate a password that must contain at least one lowercase letter, one uppercase letter, one number, and be at least 6 characters long:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function validatePassword(password) { let lowerCase = /[a-z]/g; let upperCase = /[A-Z]/g; let number = /\d/g; let minLength = 6; return password.match(lowerCase) !== null && password.match(upperCase) !== null && password.match(number) !== null && password.length >= minLength; } console.log(validatePassword("Hello@123")); // true console.log(validatePassword("hello123")); // false console.log(validatePassword("Hello@")); // false |
2. Using HTML5 pattern attribute
If we want to validate a password in an HTML form, we can use the pattern attribute to specify a regular expression that the input value must match. The browser will automatically check the validity of the input and prevent the form from being submitted if the input does not match the pattern. We can also use the title attribute to provide a message that explains the rules for the password. Here’s an example of how we can achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<!-- Create an HTML form with a password input --> <form action="/action_page.php"> <label for="password">Password</label> <!-- Use the pattern attribute to specify a regular expression for a valid password --> <input type="password" id="password" name="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w]).{8,15}" title="Must contain at least one lowercase letter, one uppercase letter, one number, and one special character, and must be between 8 and 15 characters long" required> <input type="submit" value="Submit"> </form> |
3. Using custom functions
Finally, we can use custom functions that implement our own logic and rules for validating a password. We can use any JavaScript statements and operators to check if the password meets our criteria, such as length, characters, case, etc. For example, if we want to validate a password that must contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character, we can use this function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
function validatePassword(password) { // Define an array of special characters let specialCharacters = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")"]; // Initialize variables for each criterion let hasLowercase = false; let hasUppercase = false; let hasNumber = false; let hasSpecialCharacter = false; // Loop through each character of the password for (let c of password) { // Check if it is a lowercase letter if (c >= "a" && c <= "z") { hasLowercase = true; } // Check if it is an uppercase letter else if (c >= "A" && c <= "Z") { hasUppercase = true; } // Check if it is a number else if (c >= "0" && c <= "9") { hasNumber = true; } // Check if it is a special character else if (specialCharacters.includes(c)) { hasSpecialCharacter = true; } } // Return true if all criteria are met, false otherwise return hasLowercase && hasUppercase && hasNumber && hasSpecialCharacter; } console.log(validatePassword("Hello@123")); // true console.log(validatePassword("hello\"123")); // false console.log(validatePassword("Hello'123")); // false |
If we just need to check if the string contains any of the forbidden characters for a valid password, we can use the String.includes() built-in function. It takes a substring as a parameter and returns true if the string contains the substring or false otherwise. For example, we can use this function to validate a password that must not contain any spaces or quotes:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function validatePassword(string) { let forbidden = [' ', '"', "'"]; for (let char of forbidden) { if (string.includes(char)) { return false; } } return true; } console.log(validatePassword("Hello@123")); // true console.log(validatePassword("hello\"123")); // false console.log(validatePassword("Hello'123")); // false |
That’s all about validating a password in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)