【问题标题】:Custom rule against input array in Laravel 5Laravel 5中针对输入数组的自定义规则
【发布时间】:2018-09-22 17:59:15
【问题描述】:

我正在尝试针对一组复选框制定自定义规则。请求数据正确输入

cbarray => [
  cb1 => null,
  cb2 => true,
  cb3 => true,
]

如果所有复选框都设置为 true,我正在尝试制定一个失败的验证规则。

然后我将它添加到我的 laravel 规则中

'job-payment.*' => [ new NotAllTrue ],

期望这将作为值数组发送到我的规则中,但它似乎只发送第一个属性和值。

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NotAllTrue implements Rule
{    
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return !array_reduce($value, function ($carry, $val) {
            return $carry && $val;
        }, true);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'These cannot all be true.';
    }
}

【问题讨论】:

  • 如果不将.* 添加到规则中会怎样?
  • 就是这样,谢谢@Joe

标签: php laravel laravel-5


【解决方案1】:

如果你想传递整个数组,你必须这样写:

'job-payment' => [ new NotAllTrue ],

如果你想独立验证数组的每个元素,那么:

'job-payment.*' => [ new NotAllTrue ],

【讨论】:

    猜你喜欢
    • 2015-01-26
    • 2015-06-02
    • 2015-05-08
    • 2018-10-25
    • 1970-01-01
    • 2015-09-07
    • 2015-06-14
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多