Laravel 如果值存在于另一个字段数组中则验证规则

Laravel Validation Rules If Value Exists in Another Field Array

我在 Laravel 5.4 工作,我需要一个稍微具体的验证规则,但我认为这应该很容易实现,而无需扩展 class。只是不确定如何进行这项工作..

如果 program 数组包含 'Music'.

,我想做的是使 'music_instrument' 表单字段成为必填项

我找到了这个线程 How to set require if value is chosen in another multiple choice field in validation of laravel? 但它不是解决方案(因为它从来没有得到解决)并且它不起作用的原因是提交的数组索引不是常量(未 select 在索引提交结果时不考虑编辑复选框...)

我的情况是这样的:

<form action="" method="post">
    <fieldset>

        <input name="program[]" value="Anthropology" type="checkbox">Anthropology
        <input name="program[]" value="Biology"      type="checkbox">Biology
        <input name="program[]" value="Chemistry"    type="checkbox">Chemistry
        <input name="program[]" value="Music"        type="checkbox">Music
        <input name="program[]" value="Philosophy"   type="checkbox">Philosophy
        <input name="program[]" value="Zombies"      type="checkbox">Zombies

        <input name="music_instrument" type="text" value"">

        <button type="submit">Submit</button>

    </fieldset>
</form>

如果我 select 复选框列表中的一些选项,我可能会在我的 $request 值中得到这个结果

[program] => Array
    (
        [0] => Anthropology
        [1] => Biology
        [2] => Music
        [3] => Philosophy
    )

[music_instrument] => 'Guitar'

在这里查看验证规则:https://laravel.com/docs/5.4/validation#available-validation-rules 我认为像他这样的东西应该可以工作,但我实际上什么也得不到:

  $validator = Validator::make($request->all(),[
        'program'           => 'required',
        'music_instrument'  => 'required_if:program,in:Music'
  ]);

我希望这也能奏效,但运气不好:

'music_instrument'  => 'required_if:program,in_array:Music',

想法?建议?

谢谢!

没试过,但在一般的数组字段中,你通常这样写:program.*,所以也许这样的东西会起作用:

  $validator = Validator::make($request->all(),[
        'program'           => 'required',
        'music_instrument'  => 'required_if:program.*,in:Music'
  ]);

如果它不起作用,显然你也可以用其他方式来做,例如:

$rules = ['program' => 'required'];

if (in_array('Music', $request->input('program', []))) {
    $rules['music_instrument'] = 'required';
}

$validator = Validator::make($request->all(), $rules);

我对类似问题采取的方法是在我的 Controller class 中创建一个私有函数,并使用三元表达式添加所需字段(如果它返回 true)。

在这种情况下,我有大约 20 个具有启用输入字段的复选框的字段,因此相比之下它可能有点矫枉过正,但随着您的需求增长,它可能会有所帮助。

/**
 * Check if the parameterized value is in the submitted list of programs
 *  
 * @param Request $request
 * @param string $value
 */
private function _checkProgram(Request $request, string $value)
{
    if ($request->has('program')) {
        return in_array($value, $request->input('program'));
    }

    return false;
}

如果您的其他程序也有其他字段,则可以使用此功能应用相同的逻辑。

然后在store函数中:

public function store(Request $request)
{
    $this->validate(request(), [
    // ... your other validation here
    'music_instrument'  => ''.($this->_checkProgram($request, 'music') ? 'required' : '').'',
    // or if you have some other validation like max value, just remember to add the |-delimiter:
    'music_instrument'  => 'max:64'.($this->_checkProgram($request, 'music') ? '|required' : '').'',
    ]);

    // rest of your store function
}

您可以像这样创建一个名为 required_if_array_contains 的新自定义规则...

在app/Providers/CustomValidatorProvider.php中添加一个新的私有函数:

/**
 * A version of required_if that works for groups of checkboxes and multi-selects
 */
private function required_if_array_contains(): void
{
    $this->app['validator']->extend('required_if_array_contains',
        function ($attribute, $value, $parameters, Validator $validator){

            // The first item in the array of parameters is the field that we take the value from
            $valueField = array_shift($parameters);

            $valueFieldValues = Input::get($valueField);

            if (is_null($valueFieldValues)) {
                return true;
            }

            foreach ($parameters as $parameter) {
                if (in_array($parameter, $valueFieldValues) && strlen(trim($value)) == 0) {
                    // As soon as we find one of the parameters has been selected, we reject if field is empty

                    $validator->addReplacer('required_if_array_contains', function($message) use ($parameter) {
                        return str_replace(':value', $parameter, $message);
                    });

                    return false;
                }
            }

            // If we've managed to get this far, none of the parameters were selected so it must be valid
            return true;
        });
}

并且不要忘记检查 CustomValidatorProvider.php 顶部是否有 use 语句用于我们在新方法中将验证器用作参数:

...

use Illuminate\Validation\Validator;

然后在CustomValidatorProvider.php的boot()方法中调用你新的私有方法:

public function boot()
{
    ...

    $this->required_if_array_contains();
}

然后教 Laravel 通过向 resources/lang/en/validation 中的数组添加新项以人性化的方式编写验证消息。php:

return [
    ...

    'required_if_array_contains' => ':attribute must be provided when &quot;:value&quot; is selected.',
]

现在您可以像这样编写验证规则:

public function rules()
{
    return [
        "animals": "required",
        "animals-other": "required_if_array_contains:animals,other-mamal,other-reptile",
    ];
}

在上面的示例中,animals 是一组复选框,animals-other 是文本输入,仅当 other-mamalother-reptile 值已被选中时才需要已检查。

这也适用于启用了多个 selection 的 select 输入或在请求中的一个输入中产生值数组的任何输入。

这是我的一段代码,使用 Laravel 6 验证规则

来解决这种麻烦

我尝试使用上面的代码

public function rules() 
{
    return [
      "some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
      "another_field" => ["nullable", "required_if:operacao.*,in:1"],
    ];
}

我需要当 some_array_field 的值为 1 时, another_field 必须经过验证,否则可以为空。 使用上面的代码,即使 required_if:operacao.*,1

也不起作用

如果我将 another_field 的规则更改为 required_if:operacao.0,1 WORKS 但前提是要查找的值在索引 0 中,当顺序更改时,验证失败。

所以,我决定使用自定义闭包函数

这是对我来说效果很好的示例的最终代码。

public function rules() 
{
    return [
      "some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
      "another_field" => [
          "nullable",
          Rule::requiredIf (
              function () {
                  return in_array(1, (array)$this->request->get("some_array_field"));
              }
          ),
        ]
    ];
}

希望也能解决你的烦恼!

我知道这个 post 比较老,但如果有人再次遇到这个问题。

$validator = Validator::make($request->all(),[
    'program' => 'required',
    'music_instrument'  => 'required_if:program,Music,other values'
]);