Skip to content

Instantly share code, notes, and snippets.

@zoxon
Last active March 7, 2022 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoxon/0ac5c698ec15d64143782dfa621dbc25 to your computer and use it in GitHub Desktop.
Save zoxon/0ac5c698ec15d64143782dfa621dbc25 to your computer and use it in GitHub Desktop.
/**
* Calculate password strength
* @param value password
* @returns password strength in range between 0 an 1
*/
export const getPasswordStrength = (value: string): number => {
// Minimum 8 characters
const REGEX_CHARACTER = /^.{8,}$/
// Minimum 2 uppercase,
const REGEX_UPPERCASE = /^(.*?[A-Z]){2,}.*$/
// Minimum 2 lowercase
const REGEX_LOWERCASE = /^(.*?[a-z]){2,}.*$/
// Minimum 2 number
const REGEX_NUMBERS = /^(.*?[0-9]){2,}.*$/
// Minimum 2 special characters
const REGEX_SPECIAL_CHARACTER = /(?:[^`!@#$%^&*\-_=+'/.,]*[`!@#$%^&*\-_=+'/.,]){2}/
const criteria = {
characters: REGEX_CHARACTER.test(value),
upperCase: REGEX_UPPERCASE.test(value),
lowerCase: REGEX_LOWERCASE.test(value),
specialCharacter: REGEX_SPECIAL_CHARACTER.test(value),
numbers: REGEX_NUMBERS.test(value),
}
const result = Object.values(criteria)
const total = result.length
const passed = result.filter(Boolean).length
const strength = Number.parseFloat((passed / total).toFixed(2))
return strength
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment