user53141
user53141

Reputation: 25

express-validator : show only one validation error message of a field

I am a newbie to expressjs and express-validator. I have a registration form and user has to submit email address (with other fields). my validation rule for email field with 'express-validator' looks like

req.checkBody('email', 'Email field is required').notEmpty().isEmail().withMessage('Invalid email address');

and I am using jade to print out the errors like

  if errors.length  
    .alert.alert-danger
      a.close(href='#', data-dismiss='alert', aria-label='close') ×
      for error in errors
         div=error.msg 

the above code print out all the form errors associated with a field, now the problem is, if email field is empty, it shows two error messages 'Email field is required' and 'Invalid email address'

I want to evaluate the second validation isEmail() only if the email is not empty. If empty then it need to show only one error message 'Email field is required'. Is there any solution to this ?

Upvotes: 2

Views: 8168

Answers (5)

shrhawk
shrhawk

Reputation: 781

use the bail() method

app.post('/', [
  check('username')
    .isEmail()
    .bail()
    // If username is not an email, checkBlacklistedDomain will never run
    .custom(checkBlacklistedDomain)
    .bail()
    // If username is not an email or has a blacklisted domain, checkEmailExists will never run
    .custom(checkEmailExists);
]);

Upvotes: 4

Chin2
Chin2

Reputation: 53

try this .mapped()

Returns: an object where the keys are the field names, and the values are the validation errors

Gets the first validation error of each failed field in the form of an object.

const errors = validationResult(req).mapped()

Upvotes: 0

Jasper Diongco
Jasper Diongco

Reputation: 311

  const errors = validationResult(req);
  if (errors.isEmpty()) {
    return next();
  }
  const extractedErrors = []
  errors.array({ onlyFirstError: true }).map(err => extractedErrors.push({ [err.param]: err.msg }));

  return res.status(422).json({
    errors: extractedErrors,
  });

Upvotes: 1

Kumar Subedi
Kumar Subedi

Reputation: 354

It's work for me. try this

req.getValidationResult().then(result=> {

 var errors = result.useFirstErrorOnly().array();

});

Upvotes: 1

marton
marton

Reputation: 1350

Since isEmail() seems to already validate that the string is not empty, why don't you just get rid of notEmpty()? 'Invalid email address' is informative enough for an error message if the email is left blank.

Or display errors one by one with

div=errors[0].msg

instead of

for error in errors
   div=error.msg

You could register a custom validator in express-validator that does what you want, but why complicate your life :)

Upvotes: 1

Related Questions