Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!