I'm using express-validator 5.3.1. I defined password check like this :
check('password')
.not().isEmpty().withMessage('Password can\'t be null')
.isString()
.isLength({ min: 8 }),
check('retypePassword')
.not().isEmpty().withMessage('Password can\'t be null')
.isString().withMessage('Password must be a string')
.custom((value, { req }) => {
if(value.trim() !== req.body.password.trim()) {
throw new Error ('Password confirmation does not match password');
}
}),
For testing, I send same password and retypePassword ('password') and got error :
[ { "location": "body", "param": "retypePassword", "value": "password", "msg": "Invalid value" } ]
I defined message with all error of retypePassword, so what's going on ?
When you implement a custom
validation you have to return true
if the validation succeed, otherwise you will get the "Invalid value" error message. So you just add a return true;
statement like this
.custom((value, { req }) => {
if(value.trim() !== req.body.password.trim()) {
throw new Error ('Password confirmation does not match password');
}
return true;
})