While registering a new user, I require their name
, email
, and password
. If no name
is provided, there is no need for the backend to validate the email.
I believe that the use of .bail()
in express-validator
should handle this situation, but unfortunately, all validations are still being executed.
The route being used is:
app.post('/register', validate(createUserSchema), createUser)
;
The validate()
function is as follows:
export const validate = (schemas: ValidationChain[]) => async (req: Request, res: Response, next: NextFunction) => {
await Promise.all(schemas.map(async (schema) => await schema.run(req)));
...
};
The createUserSchema
includes the following validations:
export const createUserSchema = [
body('name', 'Name is required').notEmpty().bail(),
...
];
When my request payload looks like this:
{
name: "",
email: "",
password: ""
}
The response I receive contains the following errors:
[
{
"value":"",
"msg":"Name is required",
...
}
]
This is not the expected response as it should have stopped after the first validation error. Am I missing something here?