我有一个表格,如果一个人的送货地址与其帐单地址不同,他们将选择一个单选按钮说“不”。
我需要能够检查 this 的值是什么,如果它是“否”,请检查展开的表单。如果是"is",我会跳到下面的下一个验证。 "is"部分正在工作,但“否”部分总是返回无效。有没有办法用这个库在这样的条件中嵌套验证?
这是表格的屏幕截图:
这是我针对这种情况的验证代码:
router.post('/testData2/', [
body('billingSameAsShipping', "Please Fill All Fields Of Your Billing Address").custom((value) => {
if (value === 'no') {
[
body('billingFirstName', "Please Enter Your First Name").isLength({
min: 1
}),
body('billingLastName', "Please Enter Your Last Name").isLength({
min: 1
}),
body('billingAddress1', "Please Enter Your Billing Address").isLength({
min: 1
}),
body('billingZip', "Please Enter Your Billing ZipCode").isLength({
min: 1
}),
body('billingCity', "Please Enter Your Billing City").isLength({
min: 1
}),
body('billingState', "Please Enter Your Billing State").isLength({
min: 1
})
]
} else {
return Promise.resolve();
}
}),
body('creditCardNumber', 'Please Enter A Vaild Credit Card Number').isCreditCard(),
body('expmonth', 'Exp Month Empty').isLength({
min: 1
}),
body('expyear', 'Exp Year Empty').isLength({
min: 1
}),
body('CVV', 'CVV Empty').isLength({
min: 3
})
],
(req, res) => {...
这是我们正在检查的请求对象
{
billingSameAsShipping: 'no',
billingFirstName: 'First',
billingLastName: 'Last',
billingAddress1: '450 Test Ave',
billingZip: '12345',
billingCity: 'San Diego',
billingState: 'CA',
}
最佳答案
我明白了,Express Validator 内置了条件检查
我使用 oneOf([]) 检查单选按钮的值是否为"is"或 检查帐单地址字段是否已填写。
router.post('/testData2/', [
oneOf([
[
body('billingFirstName', "Please Enter Your First Name").isLength({
min: 1
}),
body('billingLastName', "Please Enter Your Last Name").isLength({
min: 1
}),
body('billingAddress1', "Please Enter Your Billing Address").isLength({
min: 1
}),
body('billingZip', "Please Enter Your Billing ZipCode").isLength({
min: 1
}),
body('billingCity', "Please Enter Your Billing City").isLength({
min: 1
}),
body('billingState', "Please Enter Your Billing State").isLength({
min: 1
})
],
body('billingSameAsShipping').equals('yes')
], "Please Fill Out All Fields Of Your Billing Address"),
body('creditCardNumber', 'Please Enter A Vaild Credit Card Number').isCreditCard(),
body('expmonth', 'Exp Month Empty').isLength({
min: 1
}),
body('expyear', 'Exp Year Empty').isLength({
min: 1
}),
body('CVV', 'CVV Empty').isLength({
min: 3
})
],
(req, res) => {...
现在似乎工作正常。
任何人对此都有任何其他解决方案,或者看到我上面的解决方案有什么问题?
关于node.js - Express Validator - 如何处理条件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52600073/