Error with custom validation with express-Validator

Asked

Viewed 26 times

1

I’m trying to do a personalized validation with express-Validator that must return an error message if the value is different from null and has a different value than 10 characters, and which must return true if the value is null or has 10 characters.

The error message works, but even passing the value correctly still gets an error message saying that the value is invalid, and when I put the Return true in my custom validation or pass the value null instead of a string, the request only loads and returns nothing.

My personalized validation:

body("dataVenda").custom((value) => {
    if(value !== null && value.length !== 10){
        return Promise.reject("Preencha o campo data de venda de forma correta");
    }
    return true;
 }).optional({nullable: true})

That’s the way I’m passing the dice:

{
  "dataVenda": "27/08/2021"
}

And this is the error message when I pass the value correctly containing the 10 characters:

{
  "errors": [
    {
      "value": "27/08/2021",
      "msg": "Invalid value",
      "param": "dataVenda",
      "location": "body"
    }
  ]
}

1 answer

1


The correct thing would be to do the validation using the express-Validator itself and the string of expressions to do the validation you want.

This way we can use the function optional parameter nullable (you are already using) in conjunction with the function isLength passing the parameter min and max.

Follow an example:

body('dataVenda').optional({nullable: true}).isLength({min: 10, max: 10})

To learn more about express-Validator use the official documentation

  • I just edited my code and it’s working perfectly, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.