简体   繁体   中英

express-validator throw errors on valid fields

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: 'bro1@bro.com', 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM