I'm using express-validator to validate user input in typescript api. my validation chain:
export const userValidator = [
body("email").isEmpty().withMessage("email is required"),
body("email").isEmail().withMessage("email is not valid"),
body("username")
.isEmpty()
.withMessage("first name has to be longer then 2 charecters"),
body("username").isLength({ min: 2 }).withMessage("first name is required"),
body("phoneNum").isNumeric().withMessage("enter a valid phone number"),
body("password").isEmpty().withMessage("password is required"),
body("password")
.isLength({ min: 8 })
.withMessage("password must be at least 8 characters"),
body("confiremdPassword").custom((value: string, { req }) => {
if (value !== req.body.password) {
throw new Error("password have to match!");
} else {
return true;
}
}),
];
and I am checking for errors in auth.ts
:
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error: ServerError = new Error("Validation failed");
error.status = 422;
error.data = errors.array();
throw error;
}
but the result of this is very weird becuse I'm getting an array of all possible errors without a reason...
[
{ value: '[email protected]', msg: 'email is required', param: 'email', location: 'body' }, { value: 'brrrrrro', msg: 'first name has to be longer then 2 charecters', param: 'username', location: 'body' }, { value: undefined, msg: 'enter a valid phone number', param: 'phoneNum', location: 'body' }, { value: 'brorrrrrrrr', msg: 'password is required', param: 'password', location: 'body' } ] as you can see its even telling me email is empty even tho it tells me the value of it.
CodePudding user response:
You have to invert your logic.
In your code you are telling express-validator that the email field MUST be empty, otherwise it will consider it as an error.
Just add .not()
before the .isEmpty()
validator.
body("email").not().isEmpty().withMessage("email is required")
If your field is required you could also add .exists()