Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active April 19, 2020 19:46
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 nikoheikkila/3623f4e68e69a2ccd4fd1dc9fe490401 to your computer and use it in GitHub Desktop.
Save nikoheikkila/3623f4e68e69a2ccd4fd1dc9fe490401 to your computer and use it in GitHub Desktop.
Validate passwords using higher-order functions in Javascript
/** Helper for printing validator reason */
const warn = msg => {
console.warn('Invalid:', msg)
return false
}
/** Validators */
const longEnough = (password, minLength = 12) => password.length >= minLength || warn(`Password should contain ${minLength} or more characters.`)
const hasUpperCase = password => /[A-Z]+/.test(password) || warn('Password should have at least one uppercase letter.')
const hasLowerCase = password => /[a-z]+/.test(password) || warn('Password should have at least one lowercase letter.')
const hasNumbers = password => /[0-9]+/.test(password) || warn('Password should have at least one number.')
/** Higher-order function to run the given validators */
const validate = password => (...fns) => fns.every(fn => fn(password))
const validator = validate('SUP3RsECREtP4ssW0rd')
console.log(validator(
longEnough,
hasUpperCase,
hasLowerCase,
hasNumbers,
)) // => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment