问题描述
我的问题是关于Laravel 验证规则.
My question is about Laravel validation rules.
我有两个输入a
和b
. a
是具有三个可能值的选择输入:x
,y
和z
.我要编写此规则:
I have two inputs a
and b
. a
is a select input with three possible values: x
, y
and z
. I want to write this rule:
有没有办法写这样的规则?我尝试了required_with
,required_without
,但似乎无法解决我的情况.
Is there a way to write such a rule? I tried required_with
, required_without
but it seems it can not cover my case.
换句话说,如果前面的解释不够清楚:
In other words, if the previous explanation was not clear enough:
- 如果
a
==x
,则b
必须具有一个值. - 如果
a
!=x
,则b
必须为空.
- If
a
==x
,b
must have a value. - If
a
!=x
,b
must be empty.
推荐答案
您必须创建自己的验证规则.
You have to create your own validation rule.
编辑app/Providers/AppServiceProvider.php
并将此验证规则添加到boot
方法:
Edit app/Providers/AppServiceProvider.php
and add this validation rule to the boot
method:
// 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
中的错误创建消息:
(optional) Create a message for error in resources/lang/en/validation.php
:
'empty_if' => 'The :attribute field must be empty when :other is :value.',
然后在控制器中使用此规则(通过require_if
遵守原始帖子的两个规则):
Then use this rule in a controller (with require_if
to respect both rules of the original post):
$attributes = request()->validate([
'a' => 'required',
'b' => 'required_if:a,x|empty_if:a,y,z'
]);
有效!
侧面说明:我可能会使用empty_if
和empty_unless
创建一个满足此需求的程序包,并将链接发布在此处
Side note: I will maybe create a package for this need with empty_if
and empty_unless
and post the link here
这篇关于仅当另一个字段具有值时,才为必填字段,否则必须为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!