I am writing rest API using node , express web module. For validation I am using express-validator npm. I want to apply some validation rules on password field.
How can I achieve it using express-validator?
What validation rules I want to apply for password as:
I read in this link that there is a function available called regex() . So I tried it but not working at all.
My approach:
req.check("password", "Password should be combination of one uppercase , one lower case, one special char, one digit and min 8 , max 20 char long").regex("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/", "i");
Error
In express-js they have listed all the methods but did not find method / trick which solve my problem.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With