Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate a password with express-validator

I'm using express-validator for express 3.x -- when the user changes their password or signs up for an new account, they have to enter their password twice.

How would I write a custom validator that will push an error to the error stack in express-validator if the two passwords (two strings) do not match?

Something like this:

req.assert('password1', 'Passwords do not match').isIdentical(password1, password2);
var mappedErrors = req.validationErrors(true);
like image 671
chovy Avatar asked Sep 22 '12 23:09

chovy


People also ask

How do I find out my express validator password?

Steps to use express-validator to implement the logic:Validate confirmPassword by validateConfirmPassword: check('confirmPassword') and chain on all the validation with ' . ' Use the validation name(validateConfirmPassword) in the routes as a middleware as an array of validations.

How does express validator work?

According to the official website, Express Validator is a set of Express. js middleware that wraps validator. js , a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate in your apps for server-side data validation.

What is express validator check?

express-validator is a set of express. js middlewares that wraps validator. js validator and sanitizer functions.


2 Answers

I found the answer

req.assert('password2', 'Passwords do not match').equals(req.body.password1);
var mappedErrors = req.validationErrors(true);
like image 64
chovy Avatar answered Sep 24 '22 04:09

chovy


Proper way : express-validator doc:checking if password confirmation matches password

const RegistrationRules = [
  check("password")
    .notEmpty().withMessage("Password should not be empty"),
  check("confirmPassword")
    .notEmpty().withMessage("Confirm Password should not be empty")
    .custom((value,{req}) =>{
        if(value !== req.body.password){
            throw new Error('Password confirmation does not match with 
            password')
        }
        return true;
    }),]
like image 29
P R 3 A C H 3 R Avatar answered Sep 24 '22 04:09

P R 3 A C H 3 R