I've implemented the express-validator library for validating user input in a TypeScript API. Here's 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 than 2 characters"),
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;
}
}),
];
Now, in my auth.ts
file, I check for errors like this:
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error: ServerError = new Error("Validation failed");
error.status = 422;
error.data = errors.array();
throw error;
}
However, the result of this validation process is quite strange as it's showing an array of all possible errors without any clear explanation...
[
{ value: '[email protected]', msg: 'email is required', param: 'email', location: 'body' }, { value: 'brrrrrro', msg: 'first name has to be longer than 2 characters', 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' } ] The validation is even telling me that the email is empty, despite providing the value for it.