仅当另一个具有特定值时,才需要Node Js Express Validator字段
我使用express-validator来检查我的post字段。 我的问题是我想只需要其他字段具有特定的值所需的一些字段。 例如:
if person_organisation is true: person_organisation_name must be required if person_organisation is false: person_first_name must be required
有没有什么办法把这个规则放在validation架构中?
创build自定义validation:
app.use(expressValidator({ customValidators: { checkPersonName: function(name, isPerson) { return isPerson === true ? name != '' : true; }, checkOrganisationName: function(name, isPerson) { return isPerson === false ? name != '' : true; } } }));
并使用:
app.post('/registration', function(req, res) { req.checkBody( 'person_first_name', 'Please provide Your first name' ).checkPersonName(req.body.person_organisation); req.checkBody( 'person_organisation_name', 'Please provide valid organisation name' ).checkOrganisationName(req.body.person_organisation); req.getValidationResult().then(function(result) { if (!result.isEmpty()) { res.status(400).send({result: result.array()}); return; } res.json(); // when success do something }); });