Laravel 验证或
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34915547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel validation OR
提问by Ian
I have some validation that requires a url ora route to be there but notboth.
我有一些验证需要一个 url或一个路由,但不能同时存在。
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'required_without_all:route|url',
'route' => 'required_without_all:url|route',
'parent_items'=> 'sometimes|required|integer'
]);
I have tried using required_without
and required_without_all
however they both get past the validation and I am not sure why.
我试过使用required_without
,required_without_all
但是它们都通过了验证,我不知道为什么。
route
is a rule in the route
field
route
是该route
领域的规则
采纳答案by xAoc
I think the easiest way would be creation your own validation rule. It could looks like.
我认为最简单的方法是创建自己的验证规则。它可能看起来像。
Validator::extend('empty_if', function($attribute, $value, $parameters, Illuminate\Validation\Validator $validator) {
$fields = $validator->getData(); //data passed to your validator
foreach($parameters as $param) {
$excludeValue = array_get($fields, $param, false);
if($excludeValue) { //if exclude value is present validation not passed
return false;
}
}
return true;
});
And use it
并使用它
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'empty_if:route|url',
'route' => 'empty_if:url|route',
'parent_items'=> 'sometimes|required|integer'
]);
P.S. Don't forget to register this in your provider.
PS 不要忘记在您的提供商中注册它。
Edit
编辑
Add custom message
添加自定义消息
1) Add message 2) Add replacer
1) 添加消息 2) 添加替换器
Validator::replacer('empty_if', function($message, $attribute, $rule, $parameters){
$replace = [$attribute, $parameters[0]];
//message is: The field :attribute cannot be filled if :other is also filled
return str_replace([':attribute', ':other'], $replace, $message);
});
回答by Saiyan Prince
I think you are looking for required_if
:
我认为您正在寻找required_if
:
The field under validation must be present if the anotherfieldfield is equal to any value.
如果anotherfield字段等于任何值,则验证中的字段必须存在。
So, the validation rule would be:
因此,验证规则将是:
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'required_if:route,""',
'route' => 'required_if:url,""',
'parent_items'=> 'sometimes|required|integer'
]);