Search code examples
node.jsexpressexpress-validator

Custom express-validator validator doesn't work


I have problem in my code, i set validation for check email if already in database, other validation its work but in validation for email not work

this my code in Controller

AuthController.register = (req, res) => {

//EMAIL
req.checkBody('email')
.isEmail().withMessage( "must be provided" )
.custom((value, req ) => {
    return AuthController.findUserByEmail(req, value).then(user => {
        if(user == true){
            return Promise.reject('E-mail already in use');
        }
    });
}).withMessage('E-mail already in use');
}

this code not retuning error, can help me for resolve this


Solution

  • Regarding express-validator, what you are doing wrong is the unwrapping of the 2nd argument to get req; .custom() takes a validator(value, { req, location, path }) function.

    Just change it like below:

    // before
    // .custom((value, req ) => {
    // after
    .custom((value, { req }) => {
    

    ...then, if your AuthController.findUserByEmail() logic is correct, it should work as you expected ;)