【问题标题】:Laravel validation rule "different"Laravel 验证规则“不同”
【发布时间】:2018-12-21 03:33:01
【问题描述】:

我很难理解这个验证规则。基本上,我有两个字段,它们都是nullable。但是,一旦两个字段都被填满,它们就必须彼此不同。例如,我不能在两者中都输入test。如果我填写 both 字段,则此验证规则有效。

但是,当我只填写 one 的字段时,验证失败并说字段应该彼此不同,并显示以下消息:

The name and replace must be different.

我检查了提交给我的表单请求的内容,如下:

"name" => null
"replace" => "test"

我的验证规则的剥离版本:

public function rules()
{
    return [
        'name' => 'different:replace|nullable',
        'replace' => 'different:name|nullable',
    ];
}

有人可以向我解释一下我对这个验证规则有什么误解吗? null 值不符合此规则吗?

【问题讨论】:

    标签: php laravel validation


    【解决方案1】:

    如果您查看Illuminate\Validation\Concerns\ValidatesAttributes (vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php:432) 规则中的validateDifferent 函数:

    public function validateDifferent($attribute, $value, $parameters)
    {
        $this->requireParameterCount(1, $parameters, 'different');
    
        foreach ($parameters as $parameter) {
            $other = Arr::get($this->data, $parameter);
    
            if (is_null($other) || $value === $other) {
                return false;
            }
        }
    
        return true;
    }
    

    正如你在 if 情况下看到的,如果另一个值为 null,则规则将失败。

    if (is_null($other) || $value === $other)
    

    【讨论】:

    • 应该检查过那里.. 至少学到了一些新东西,谢谢 :)
    • @Hardist Np 有美好的一天! :)
    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 2020-06-25
    • 2020-06-09
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多