Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate password using express-validator npm

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:

  1. min 8 char long.
  2. At least one uppercase.
  3. At least one lower case.
  4. At least one special character.

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

enter image description here

In express-js they have listed all the methods but did not find method / trick which solve my problem.

like image 949
Sunil Sharma Avatar asked Jan 13 '16 07:01

Sunil Sharma


2 Answers

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.

like image 60
Chris Payne Avatar answered Sep 19 '22 17:09

Chris Payne


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.

like image 33
tbking Avatar answered Sep 19 '22 17:09

tbking