How to validate password using express-validator npm How to validate password using express-validator npm express express

How to validate password using express-validator npm


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");


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.


Chosen answer is incomplete as it's missing validation for special characters. Correct answer should be:

req.checkBody("password", "Password must include one lowercase character, one uppercase character, a number, and a special character.").matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/, "i");

Only real difference is that I added the (?=.*[^a-zA-Z0-9]) expression which ensures a user is using a character that's not a number or letter.