Reputation: 3662
export function valUPM() {
return (req: Request, _res: Response, next: NextFunction) => {
req
.checkBody(
"paymentType",
`paymentType: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
if (req.body.paymentType === "USP") {
req
.checkBody(
"storeId",
`storeId: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
} else if (req.body.paymentType === "CC") {
if (req.body.register) {
req
.checkBody(
"register",
`register: ${messages.getFromSession(req, "mustBeBoolean")}`
)
.isBoolean();
} else {
req
.checkBody(
"register",
`register: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
}
}
req.getValidationResult().then(errs => {
if (errs.isEmpty()) {
return next();
}
const error = new BFFError(
400,
"BadRequest",
1,
errs.array().map(error => {
return { [error.param]: error.msg };
})
);
return next(Error(JSON.stringify(error)));
});
};
}
After the change to API how to implement this type of logic in express validators
Calling req.checkBody or the required validation function inside an if loop did the trick like shown above but after change in API how can this be implemented I tried a work around of checking the paymentTYpe as a custom validator and implementing the checks and throwing the message inside the custom validator but the keys change .
Using the current APi what is the proper way to do this as this will be useful for all the people who would want to update from 3.0.0s to latest express-validator API
Upvotes: 5
Views: 2985
Reputation: 41440
Conditional validation support is not present yet in express-validator v5.x.x
, but it is coming soon.
Here's the Pull Request, in case you would like to give your feedback on the API: https://github.com/express-validator/express-validator/pull/658
However, please note that the legacy API (the one that uses req.checkBody()
, req.getValidationResult()
, etc, hasn't been removed from express-validator yet.
You can keep using it in v5.x.x
just as you would in v3.x.x
. It's just not recommended to do so, as it's deprecated and might be removed when v6 is due (not yet!).
All docs are here, side by side with the newer APIs docs.
Disclaimer: I'm an express-validator maintainer.
Upvotes: 3