Sunil Sharma Sunil Sharma - 1 year ago 426
Node.js Question

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


enter image description here

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

Answer Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download