node.jsexpress-validator

nodejs express-validator: validate email format only if value exists


I have following validation rules (nodejs, express-validator)

---------------------
check('email').not().isEmpty().withMessage('email is required'),
check('email').isEmail().withMessage('email not valid'),
---------------------

Now if I submit the form without an email address value it will have the following errors.

email is required 
email not valid

I want to check email format only if email value exists, so that only one error message will be there, either 'email is required' or 'email not valid'.

any suggestions?


Solution

  • According to the documentation, .bail() can be used to stop running further validations if any of the previous ones in the chain have failed.

    Try this:

    check("email")
      .not()
      .isEmpty()
      .withMessage("email is required")
      .bail()
      // if email is empty, the following will not be run
      .isEmail()
      .withMessage("email not valid");