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);
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.
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.
express-validator is a set of express. js middlewares that wraps validator. js validator and sanitizer functions.
I found the answer
req.assert('password2', 'Passwords do not match').equals(req.body.password1);
var mappedErrors = req.validationErrors(true);
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;
}),]
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