Skip to content

Instantly share code, notes, and snippets.

@vithalreddy
Created May 7, 2020 09:49
Show Gist options
  • Save vithalreddy/c0d486f23f8b3e96ec14c49109b8dc08 to your computer and use it in GitHub Desktop.
Save vithalreddy/c0d486f23f8b3e96ec14c49109b8dc08 to your computer and use it in GitHub Desktop.
Password Strength Validation function for Javascript/Typescript with configurable options
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