Using express-validator to validate password to have minimum 8 characters including at least one special character and at least one number

May 3, 2019

Q How to use express-validator to validate passwords to have minimum 8 characters including at least one special character at least one number?

A The regular expression used to validate a password which will follow the above-mentioned pattern is as follows

While using express-validator, we use  the chain method .matches() to check the input password against regular expression as follows

The above validator checks whether the request body of the post request has a password which is a minimum of 8 characters long,

and contains an alphabet and a special character.

 

If there are any validation errors, it can be obtained using  validationResult(req)

 

To display only the first error at a time we add the following object to errors.array() 

Now handling the error part looks like this

So the final code looks like this

 

3 Comments

  • Franches Caartis May 4, 2019 at 8:40 pm

    Hi, Neat post.

  • Ahsan Masood July 23, 2019 at 8:09 pm

    the regex given does not work when any dot “.” appears in the password

  • Anatolia August 19, 2019 at 5:15 pm

    Thanks for notifying Ahsan. The regex is updated by the developers here. Please check

Leave a Reply

Your email address will not be published. Required fields are marked *