尊重验证:当一个表单有多个同名字段时,正确的验证规则是什么?
Respect Validation: What's the right validation rule when a form has several fields with the same name?
我有一个只有字段的表单:
- 问题
- 选择
Choice 是一个数组,因为一个问题有多个答案,用户可以根据需要添加任意多个。
我只需要验证这些不为空,所以我尝试了:
$validation = $this->c->validator->validate($request, [
'question' => v::notEmpty(),
'choice[]' => v::ArrayVal()->each()->notEmpty()
]);
但它不允许我保存任何条目。如果我将 choice[] 保留为 "choice",它会验证每个条目。我认为规则一定是错误的。
您可以使用 KeySet 验证器:
$response = v::keySet(
v::key('question', v::notEmpty()),
v::key('choice', v::arrayVal())
)->validate($request);
如果您使用给定值:
$request = [
'question' => 'What is your first name?',
'choice' => []
];
验证returnstrue
.
如果您使用给定值:
$request = [
'question' => 'What is your first name?',
'choice' => ''
];
验证returnsfalse
.
我有一个只有字段的表单:
- 问题
- 选择
Choice 是一个数组,因为一个问题有多个答案,用户可以根据需要添加任意多个。
我只需要验证这些不为空,所以我尝试了:
$validation = $this->c->validator->validate($request, [
'question' => v::notEmpty(),
'choice[]' => v::ArrayVal()->each()->notEmpty()
]);
但它不允许我保存任何条目。如果我将 choice[] 保留为 "choice",它会验证每个条目。我认为规则一定是错误的。
您可以使用 KeySet 验证器:
$response = v::keySet(
v::key('question', v::notEmpty()),
v::key('choice', v::arrayVal())
)->validate($request);
如果您使用给定值:
$request = [
'question' => 'What is your first name?',
'choice' => []
];
验证returnstrue
.
如果您使用给定值:
$request = [
'question' => 'What is your first name?',
'choice' => ''
];
验证returnsfalse
.