I currently have 2 custom validators set up for the fields email
and phone
.
check('phone')
.not()
.isEmpty()
.withMessage('Phone should not be empty')
.custom(async phone => {
const phoneCheck = await User.findOne({ phone: phone });
if (phoneCheck !== null) {
return Promise.reject();
}
}).withMessage('Phone is already in use.')
The validation for phone
seems to be working fine without throwing any errors. However, the validation for email
is causing an error on the browser.
check('email')
.not()
.isEmpty()
.withMessage('Email should not be empty')
.isEmail()
.withMessage('Email must be valid')
.custom(async email => {
const emailCheck = await User.findOne({ email: email });
if (emailCheck !== null) {
return Promise.reject();
}
}).withMessage('Email is already in use.')
Interestingly, when testing the API in Postman, both errors are thrown for the phone
validation.
This is how I am handling errors in my API function:
const errors = validationResult(req);
if (!errors.isEmpty()) {
const erroredFields = errors.array();
const newErrors = erroredFields.map(err => {
return {
field: {
name: err.param,
error: err.msg
}
}
})
res.status(401).json({
message: 'Validation Error',
errors: newErrors
})
}
Results from the browser:
Results from Postman:
Both inputs produce the same output.
I am using Nuxt with Express. Is there something wrong with how I am implementing custom validations?