Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate two fields that should be equal in Node.js and Express?

I am using express-validator for the first time and I can't find a way to assert if two fields are equal (if that can be done at all).

Example: A form containing 2 times an email address (one as standard confirmation) is submitted. I want to check that the fields match.

I found a workaround by myself which works but I wonder if I'm not just doing something unnecessary. Here is the code (the data is coming through an ajax call):

//routes.js

function validator(req, res, next) {

  req.checkBody('name', 'cannot be empty').notEmpty();
  req.checkBody('email', 'not valid email').isEmail();

  var errors = req.validationErrors(); // up to here standard express-validator

  // Custom check to see if confirmation email matches.

  if (!errors) errors = [];
  if (email !== email_confirm){
    errors.push({param: 'email_confirm', msg: 'mail does not match!', value: email_confirm})
  }

  if (errors.length > 0) {
    res.json({msg: 'validation', errors:errors}); // send back the errors
  }
  else {
    // I don't want to insert the email twice in the DB
    delete req.body.email_confirm
    next(); // this will proceed to the post request that inserts data in the db
  }
};

So my question is: is there a native method in express-validator to check if (email===email_confirm)? If not is there a better/more standard way to do what I have done above? I'm quite new to node/express in general. Thank you.

like image 662
Tommy Avatar asked Dec 06 '22 13:12

Tommy


2 Answers

To achieve this goal with the new check API in express-validator version 4, you would need to create a custom validator function in order to be able to access the request, like this:

router.post(
    "/submit",
    [
    // Check validity
    check("password", "invalid password")
        .isLength({ min: 4 })
        .custom((value,{req, loc, path}) => {
            if (value !== req.body.confirmPassword) {
                // trow error if passwords do not match
                throw new Error("Passwords don't match");
            } else {
                return value;
            }
        })
    ],
    (req, res, next) => {
        // return validation results
        const errors = validationResult(req);

        // do stuff
    });
like image 87
Martin Reiche Avatar answered Jan 04 '23 03:01

Martin Reiche


As express-validator is express middleware for validator.js, you can use equals():

req.checkBody('email_confirm', 'mail does not match').equals(req.body.email);
like image 30
haotang Avatar answered Jan 04 '23 03:01

haotang