我的评级系统存在验证问题。这两个字段都需要在特定条件下进行验证。
f1 = 字段 1 -> 从 1 到 5 的单选;
f2 = 字段 2 -> 文本区域;
这是我的验证规则:
$validatedData = $request->validate([
'f1' => 'sometimes|nullable|integer|min:1|max:5',
'f2' => 'sometimes|nullable|string|max:255',
]);
我需要为 f2 添加验证规则,以便仅当 f1 <= 3.
时才需要它目前,我有
'sometimes|nullable|required_if:f1,<,4|string|max:255'
。
以下是案例:
情况 1 -> 如果我用 f1 提交表格 <= 3 and f2 empty = It correctly returns an error because f2 is required if f1 <= 3;
案例 2 -> 如果我提交表单时 f1 >= 4 且 f2 为空 = 它可以正常工作。
案例 3 -> 如果我提交 f1 为空且 f2 为空的表单 = 它会返回错误,因为如果 f1 则需要 f2 <= 3. However, it should be nullable in this case.
此外,如果 f2 不为空,我需要将 f1 设置为必需。
要完成复杂的验证,您可以在数组中使用 closures 来分隔每个规则,而不是使用管道“|”的字符串。
闭包接收属性的名称、属性的值和 如果验证失败,则应调用 $fail 回调:
$validatedData = $request->validate([
'f1' => [
'nullable',
'integer',
'between:1,5',
function (string $attribute, mixed $value, Closure $fail) {
if (empty($value) && !empty($this->input('f2'))) {
$fail('f1 is required if f2 is not empty.');
}
},
],
'f2' => [
'nullable',
function (string $attribute, mixed $value, Closure $fail) {
if (empty($value) && $this->input('f1') <= 3) {
$fail('f2 is required if f1 <= 3.');
}
if ($value) {
$fail('f2 is required if f1 <= 3.');
}
},
],
]);