Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw a custom error with express-validator?

I am validating a form through the POST method. I want to push an error into express-validator when an email address is already registered, so when I do req.validationErrors() it is included. Something like this:

req.checkBody('inputFirstName', 'First name empty').notEmpty();
req.checkBody('inputLastName', 'Last name empty').notEmpty();
db.User.find({email: req.body.inputEmail}, function (err, user){
        if(user){
            var error = {param: "inputEmail", msg: "Email address already registered", value: ''};
            expressValidator._errors.push(error);
        }
    });

Thanks.

like image 572
rasco22862 Avatar asked Nov 23 '13 21:11

rasco22862


2 Answers

You can do something like this:

req.checkBody('inputFirstName', 'First name empty').notEmpty();
req.checkBody('inputLastName', 'Last name empty').notEmpty();
var errors = req.validationErrors();
db.User.find({email: req.body.inputEmail}, function (err, user){
        if(user){
            var error = {param: "inputEmail", msg: "Email address already registered", value: req.body.email};
            if (!errors) {
                errors = [];
            }
            errors.push(error);
        }

        // Here need  to be next part of action - not outside find callback!
    });

But I think it's a bad idea to put some mongoose validation on request side validation. You can use some schema methods, e.g. pre save, make validation there.

like image 145
Krzysztof Wilczek Avatar answered Oct 08 '22 20:10

Krzysztof Wilczek


Here is one example that you should put in your validator:

   // Validates data when registering new user.
   exports.registerNewUser = [        
     body('email').
       exists().withMessage("Email is required").
       isEmail().withMessage("Not a valid email").bail().
       // bail() is important so that in case some of previous validations fail, you don't call db function
       custom(async (val) => {
        // Check if the email is already taken
        try {
            const user = await User.getOneUserByEmail({email: val});
            // check for example if user exists or that it is not closed
            if(user && user.status!=="closed") return false;
            else return true;
        } catch(error) {
            // if there is an error, always return false
            console.log(error);
            return false;
        }
    }).withMessage("Email already taken")
  ]

You should also import:

const { body } = require('express-validator/check');
like image 34
Nebojsa Avatar answered Oct 08 '22 20:10

Nebojsa