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.
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.
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');
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