How to validate password using express-validator npm

I believe the accepted answer is outdated. RegExp and express-validator are not the best ways to validate passwords in 2017, as the obscurity of regular expressions makes the app unmaintainable and prone to bugs.

password-validator makes it easy to define password rules and maintain them. Here's a sample:

var passwordValidator = require('password-validator');

var schema = new passwordValidator();

schema
  .is().min(8)
  .is().max(100)
  .has().uppercase()
  .has().lowercase();

console.log(schema.validate(req.body.password)); // prints a boolean

PS: I'm the author of the password-validator.


Using the built in validators of express-validator I was able to use built in validators without a regex to check the password.

const validateStrongPassword = body("password")
  .isString()
  .isLength({ min: 8 })
  .not()
  .isLowercase()
  .not()
  .isUppercase()
  .not()
  .isNumeric()
  .not()
  .isAlpha();

This verifies that there is at least one non letter character, one lowercase letter, one uppercase letter, a minimum length and that there are letters in the password.


The link you're referring to is almost 3 years old. Since then, the API of validator changed.

To check against a regular expression, use .matches():

req.check("password", "...").matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/, "i");