Search code examples
javascriptexpressnuxt.jsexpress-validator

Custom express Validator for 2 fields


I have 2 custom validators for 2 fields, email and phone.

check('phone')
      .not()
      .isEmpty()
      .withMessage('Phone shouldnt be empty')
      .custom(async phone => {
        const phonechk = await User.findOne({ phone: phone });
        if (phonechk !== null) {
          return Promise.reject();
        }
      }).withMessage('Phone is already in use.')

This above check does not throw any error but this one :

  check('email')
    .not()
    .isEmpty()
    .withMessage('Email shouldnt be empty')
    .isEmail()
    .withMessage('Email Should be Valid')
    .custom(async email => {
      const emailCheck = await User.findOne({ email: email });
      if (emailCheck !== null) {
        return Promise.reject();
      }
    }).withMessage('Email is already in use.'),

Throws an error on the browser.

the thing I noticed when I tested the API in postman the phone validation throw both errors .

that's how im handling the errors in my api function :

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const arEr = errors.array();
    const newErrors = arEr.map(err => {
      return {
        field: {
          name: err.param,
          error: err.msg
        }
      }
    })
    res.status(401).json({
      message: 'Validation Error',
      errors: newErrors
    })
  }

Result from browser :

1

Result from postman :

2

both are same input ^

I'm using nuxt with express.

Is there anything wrong I'm doing in using custom validation?


Solution

  • It turned out the problem is not from express-validator, Since I'm using vue-tel-iput component for phone numbers. the component was formatting the phone number with white spaces so it was submitting the phone in the wrong form. I trimmed the white spaces using .replace(/\s+/g, "") and the validation worked correctly