3

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?

1 Answer 1

3

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.