Created
May 7, 2020 09:49
-
-
Save vithalreddy/c0d486f23f8b3e96ec14c49109b8dc08 to your computer and use it in GitHub Desktop.
Password Strength Validation function for Javascript/Typescript with configurable options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const passwordConfig = Object.freeze({ | |
minLength: 8, | |
atleaseOneLowercaseChar: true, | |
atleaseOneUppercaseChar: true, | |
atleaseOneDigit: true, | |
atleaseOneSpecialChar: true, | |
}); | |
function verifyPasswordStrength(password) { | |
if ( | |
passwordConfig.minLength && | |
password.length < passwordConfig.minLength | |
) { | |
throw new Error( | |
`Your password must be at least ${passwordConfig.minLength} characters` | |
); | |
} | |
if ( | |
passwordConfig.atleaseOneLowercaseChar && | |
password.search(/[a-z]/i) < 0 | |
) { | |
throw new Error( | |
"Your password must contain at least one lowercase character." | |
); | |
} | |
if ( | |
passwordConfig.atleaseOneUppercaseChar && | |
password.search(/[A-Z]/) < 0 | |
) { | |
throw new Error( | |
"Your password must contain at least one uppercase character." | |
); | |
} | |
if (passwordConfig.atleaseOneDigit && password.search(/[0-9]/) < 0) { | |
throw new Error("Your password must contain at least one digit."); | |
} | |
if (passwordConfig.atleaseOneSpecialChar && password.search(/\W/) < 0) { | |
throw new Error( | |
"Your password must contain at least one special character." | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment