Javascript Function to Check Password Complexity
Javascript Function to Check Password Complexity: ensure an input type='password' element contains a password that has [1]at least 1 number. [2] at least 1 lowercase letter. [3] at least 1 uppercase letter. ..
Home
Short:
/*----------------------------------------------------- function to ensure an input type=password element contains a password that has ... [1] at least 1 number [2] at least 1 lowercase letter [3] at least 1 uppercase letter [4] a special character #?!@$%^&*- [5] has a value whose length is between inputPassword.minLength inputPassword.maxLength BE SURE [inputPassword] HAS A [minlength] and [maxlength] ie ...
OR THE [chrlen] PARAMETER WILL FAIL ------------------------------------------------------ */ function validPassword(inputPassword) { const minLength = inputPassword.minLength, maxLength = inputPassword.maxLength; if ((minLength === -1) || (maxLength === -1)) { console.log("Error: function validatePassword(): object [inputPassword] does not have a minlength and/or maxlength attribute"); return false; } const pattern = new RegExp(`^.{${minLength},${maxLength}}$`), strPwd = inputPassword.value.trim(); const validations = { password_has_spaces: !/\s/.test(strPwd), // we DONT want spaces password_has_no_number: /\d/.test(strPwd), // we DO want a number password_has_no_lowercase_letter: /[a-z]/.test(strPwd), // we DO want lowercase password_has_no_uppercase_letter: /[A-Z]/.test(strPwd), // we DO want uppercase password_has_no_special_character: /[#?!@$%^&*\-]/.test(strPwd), // we DO want special chr password_length_not_7_to_10_characters: pattern.test(strPwd) // we DO want len 7 - 10 chr }; // Filter out keys with false values (i.e., failed validations) const failedValidations = Object.keys(validations).filter(key => !validations[key]); return failedValidations; } //=> validatePassword
Example password validator function usage:
let pwdValid = validPassword(document.querySelector("#inpPassword")); if(pwdValid && (pwdValid.length > 0)) { // remove underscores from password items [pwdTest] that failed const cleanedPwdValid = pwdValid.map(str => str.replace(/_/g, " ")); // create html to display things wrong with new password let strFailed = cleanedPwdValid.join("\r\n -"), msg ="Your new password is missing the following:\r\n\ -" + strFailed; alert(msg); }
Try Javascript Password Validator Function
Check Password
show password
source code home