Last active
April 19, 2020 19:46
-
-
Save nikoheikkila/3623f4e68e69a2ccd4fd1dc9fe490401 to your computer and use it in GitHub Desktop.
Validate passwords using higher-order functions in Javascript
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
/** 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