laravel 在验证规则中使用多个 required_if
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22336965/
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
Using multiple required_if in a validation rule
提问by Isaias
I have a select
with many options, I want another select
to be required when the first has an specific value.
我有select
很多选项,我希望select
当第一个具有特定值时需要另一个。
<select id="category" name="category">
<option value="a">Option A</option>
<option value="b">Option B</option>
<option value="c">Option C</option>
<option value="d">Option D</option>
<option value="e">Option E</option>
<option value="f">Option F</option>
</select>
<select id="subcategory" name="subcategory">
<option value="a">Suboption A </option>
<option value="b">Suboption B </option>
<option value="c">Suboption C </option>
<option value="d">Suboption D </option>
<option value="e">Suboption E </option>
</select>
I want the second select
to be required when the user chooses option a,b or f. Is it correct to use the next rule in the controller code that validates the inputs?:
我希望select
当用户选择选项 a、b 或 f 时需要第二个。在验证输入的控制器代码中使用下一条规则是否正确?:
$rules = array(
'category' => 'alpha|in:a,b,c,d,e,f|required|size:1',
'subcategory' => 'alpha|
in:a,b,f|
required_if:category,a|
required_if:category,b|
required_if:category,f|
size:1'
);
Is there (another or) a better way to validate this?
是否有(另一种或)更好的方法来验证这一点?
采纳答案by The Alpha
You may register a custom validation rule to check this, for example:
您可以注册自定义验证规则来检查这一点,例如:
Validator::extend('required_if_anyOfThese', function($attribute, $value, $parameters)
{
// Check here whether any of those Inputs are available and make sure
// what to do, return true or false depending on the result
$attribute is field name "subcategory"
$value will contain the value of the field
$parameters will contain the parameters, array => a,b,f
});
Use it as:
将其用作:
$rules = array('subcategory' => 'required_if_anyOfThese:a,b,f');
Read more on Laravel Website.
在Laravel 网站上阅读更多内容。
回答by MohitMamoria
Or, you can simply use it like so.
或者,您可以像这样简单地使用它。
$rules = array('subcategory' => 'required_if:category,a,b,f');
Laravel takes all the parameters except the first one as array and then checks if the value of first parameter is matched with the rest of parameters using in_array
method.
Laravel 将除第一个参数以外的所有参数作为数组,然后使用in_array
方法检查第一个参数的值是否与其余参数匹配。