How to validate a password in Javascript with Regular Expressions

Mark O'Neill
February 24, 2021

Validating a password is a frustrating and common requirement for most websites these days. Regular expressions can help us validate multiple password rules without needing external libraries or complex functions.

copy code
javascript
function validatePassword(pwd) => {

// set password rules
  const charLimit = 8
  const lowerAlpha = new RegExp('^(?=.*[a-z])') //contains a lowercase letter
  const upperAlpha = new RegExp('^(?=.*[A-Z])') //contains an uppercase letter
  const numeric = new RegExp('^(?=.*[0-9])') // contains a number 
  const spcChar = new RegExp('^(?=.*[!@#$%^&*])') //contains one of these special characters
  
  let errors = []
  
  if (pwd.length < charLimit) {
    errors.push(`Password needs to be ${charLimit} characters`)
  }
  
  if (!lowerAplha.test(pwd)) {
    errors.push(`At least 1 lowercase letter required`)
  }
  
  if (!upperAlpha.test(pwd)) {
    errors.push(`At least 1 uppercase letter required`)
  }
  
  if (!numeric.test(pwd)) {
    errors.push(`At least 1 number required`)
  }
  
  if (!spcChar.test(pwd)) {
    errors.push(`At least 1 special character required`)
  }
  
  return errors 
}

You can then check to see if there are any violations with a potential password and return all issues at once to the user.

copy code
javascript
...

const validations = validatePassword("gizmo1")
//Output ["Password requires at lestr"]

if (validations.length == 0) {
  console.log("password is valid")
  return
}

console.log("Password has the following errors:", validations)

...

This method saves you from checking one issues at a time, or checking all of them at once and returning vague error messages.

Know a better answer? Join our our community and let us know.