php 具有多个值的 required_if laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36274940/
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
Required_if laravel with multiple value
提问by Donny Akhmad Septa Utama
I have a dropdown menu like this:
我有一个这样的下拉菜单:
<select name="selection">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<input type="text" name="stext">
I want the following in laravel:
我想在 laravel 中有以下内容:
public static myfunction(){
$input = \Input::only('selection','stext');
$rule = array(
'selection' => 'required',
'stext' => 'required_if:selection,2,3',
);
$validate = \Validator::make($input,$rule);
}
But if I select option 1, stext
is still required. Why?
How can I fix it?
但是如果我选择选项1,stext
仍然需要。为什么?我该如何解决?
回答by lephleg
You just have to pass all the values as parameters separated by comma:
您只需将所有值作为以逗号分隔的参数传递:
$rules = array(
'selection' => 'required',
'stext' => 'required_if:selection,2,3'
);
回答by RDev
I think that the require_if validation accept only one value per time. Try to change your validation code as below:
我认为 require_if 验证每次只接受一个值。尝试更改您的验证代码如下:
$rule = array(
'selection' => 'required',
'stext' => 'required_if:selection,2|required_if:selection,3',
);
EDIT: Check LePhleg answer, is more cleaner. At the time of the answer that was not possible, just check the question, he was using the same method but not worked.
编辑:检查 LePhleg 的答案,更干净。在回答不可能的时候,只需检查问题,他正在使用相同的方法但没有奏效。
回答by Jignesh Joisar
try this one
试试这个
if single match value then used like that
如果单个匹配值然后像那样使用
'stext' => 'required_if:selection,2'
if you have multiple value then used like that (separated by comma)
如果您有多个值,则像这样使用(用逗号分隔)
'stext' => 'required_if:selection,2,3'
for more information see documentation required_if
有关更多信息,请参阅文档required_if
回答by Shyam Achuthan
You can go ahead with sometimes validation for laravel. you can define a custom closure as in the below example
您有时可以继续验证 laravel。您可以定义一个自定义闭包,如下例所示
public static myfunction(){
$input = \Input::only('selection','stext');
$rule = array(
'selection' => 'required'
);
$validator->sometimes('stext', 'required', function($input){
return (($input->selection == 1) || ($input->selection == 2));
});
$validate = \Validator::make($input,$rule);
}