Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda