admin管理员组文章数量:1393063
I use express-validator to check my post fields. My Problem is I want to make some fields required only if other fields have a specific values. eg:
if person_organisation is true:
person_organisation_name must be required
if person_organisation is false:
person_first_name must be required
Is there any way to put this rules in Validation Schema??
I use express-validator to check my post fields. My Problem is I want to make some fields required only if other fields have a specific values. eg:
if person_organisation is true:
person_organisation_name must be required
if person_organisation is false:
person_first_name must be required
Is there any way to put this rules in Validation Schema??
Share Improve this question asked Apr 23, 2017 at 14:43 medkhelifimedkhelifi 1,1413 gold badges19 silver badges40 bronze badges1 Answer
Reset to default 4Create custom validation:
app.use(expressValidator({
customValidators: {
checkPersonName: function(name, isPerson) {
return isPerson === true ? name != '' : true;
},
checkOrganisationName: function(name, isPerson) {
return isPerson === false ? name != '' : true;
}
}
}));
and use:
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
});
});
版权声明:本文标题:javascript - Node Js Express Validator required field only if another have a specific value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744657889a2618075.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论