问题描述
express-validator,如何仅在存在另一个字段时才使该字段为必填字段?
const validateUpdateStore = () => {
return [
body('logo').optional().isURL().withMessage('invalid url'),body('email')
.optional()
.isEmail()
.withMessage('email is invalid')
.trim()
.escape(),body('phone').optional().isInt().withMessage('integers only!'),body('account_number').optional().isInt().withMessage('integers only!'),body('bank_code').optional().isInt().withMessage('integers only!'),];
};
仅在提供bank_code
时,我想将字段account_number
设置为必填字段,反之亦然
解决方法
6.1.0的
版本express-validator添加了对条件验证器的支持。我目前在文档中没有看到它,但是有pull request带有更多信息。看来您应该能够按照以下方式定义验证:
const validateUpdateStore = () => {
return [
body('logo').optional().isURL().withMessage('invalid url'),body('email')
.optional()
.isEmail()
.withMessage('email is invalid')
.trim()
.escape(),body('phone').optional().isInt().withMessage('integers only!'),body('account_number')
.if(body('bank_code').exists()) // if bank code provided
.not().empty() // then account number is also required
.isInt() // along with the rest of the validation
.withMessage('integers only!'),body('bank_code')
.if(body('account_number').exists()) // if account number provided
.not().empty() // then bank code is also required
.isInt() // along with the rest of the validation
.withMessage('integers only!'),];
};