我的问题是关于Laravel validation rules。
我有两个输入a
和b
。 a
是一个包含三个可能值的选择输入:x
,y
和z
。我想写这条规则:
仅当b
值a
时,
x
必须的值。 而b
必须为空。
有没有办法写这样的规则?我尝试了required_with
,required_without
,但似乎无法涵盖我的情况。
换句话说,如果前面的解释不够清楚:
a
== x
,b
必须有值。a
!= x
,则b
必须为空。答案 0 :(得分:1)
您必须创建自己的验证规则。
修改app/Providers/AppServiceProvider.php
并将此验证规则添加到boot
方法:
// Extends the validator
\Validator::extendImplicit(
'empty_if',
function ($attribute, $value, $parameters, $validator) {
$data = request()->input($parameters[0]);
$parameters_values = array_slice($parameters, 1);
foreach ($parameters_values as $parameter_value) {
if ($data == $parameter_value && !empty($value)) {
return false;
}
}
return true;
});
// (optional) Display error replacement
\Validator::replacer(
'empty_if',
function ($message, $attribute, $rule, $parameters) {
return str_replace(
[':other', ':value'],
[$parameters[0], request()->input($parameters[0])],
$message
);
});
(可选)在resources/lang/en/validation.php
:
'empty_if' => 'The :attribute field must be empty when :other is :value.',
然后在控制器中使用此规则(使用require_if
来遵守原始帖子的两个规则):
$attributes = request()->validate([
'a' => 'required',
'b' => 'required_if:a,x|empty_if:a,y,z'
]);
有效!
旁注:我可以使用empty_if
和empty_unless
为此需求创建一个包,并在此处发布链接
答案 1 :(得分:0)
<强> required_if:anotherfield,值,... 强> 如果anotherfield字段等于任何值,则验证字段必须存在且不为空。
'b' => 'required_if:a,x'
答案 2 :(得分:0)
我知道答案还为时过晚,但是对于那些后来才知道这个问题的人来说,Laravel有自己的方法来在存在另一个字段时要求一个字段。该方法名为“ required_with”,您可以找到更多有关here的信息。