Laravel 自定义验证规则引用其他请求参数

fud*_*udo 8 validation rules laravel laravel-validation php-7

我正在尝试创建一个接受参数的自定义验证规则,但该参数是请求中另一个字段的名称,就像规则一样required_with

我可以轻松处理规则中给定的参数,但我正在努力找出如何检索其他字段值。

目前我正在创建我的规则类

class MyClassRule
{
    public function validate($attribute, $value, $parameters, $validator) : bool
    {
        // do some stuff here to return true/false
    }
}
Run Code Online (Sandbox Code Playgroud)

并在我的服务提供商中注册

Validator::extend('my_rule', 'path\to\MyClassRule@validate');
Run Code Online (Sandbox Code Playgroud)

所以我可以在我的请求中使用它

public function rules()
{
    return [
        'field' => ['my_rule'],
    ];
}
Run Code Online (Sandbox Code Playgroud)

我想做的是

public function rules()
{
    return [
        'other_field' => [...],
        'field'       => ['my_rule:other_rule'],
    ];
}
Run Code Online (Sandbox Code Playgroud)

并使用other_field我的规则类中的值,但validate()$parameters值只是['other_field']。即包含其他字段名称而不是其值的数组。

我怎样才能做到这一点?

小智 8

我在 Laravel 7.x 中运行它。

就我而言,我试图制定一项规则来比较表单中的两个字段是否彼此相等。

让我们按照 Laravel 文档的指示创建一个新的规则对象。
https://laravel.com/docs/7.x/validation#custom-validation-rules


下面是创建 Rule 类模板的控制台命令。
php artisan make:rule StrEqualTo

下面是生成的自定义规则类,其中包含逻辑的完整实现。

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class StrEqualTo implements Rule{
    private $referredField = null;

    public function __construct(string $referredField){
        $this->referredField = $referredField;
    }

    public function passes($attribute, $value){
        return request()->input($this->referredField) === $value;
    }

    public function message(){
        return 'The :attribute must match with' . $this->referredField . '.';
    }
}
Run Code Online (Sandbox Code Playgroud)

我们首先创建一个私有属性和一个带参数的构造函数,该参数将接受要引用的字段的“name”属性。然后,我们将构造函数参数中的值分配给规则类中的私有属性。

private $referredField = null;

public function __construct(string $referredField){
        $this->referredField = $referredField;
}
Run Code Online (Sandbox Code Playgroud)

正如 Laravel 文档中所述,如果验证成功,此函数必须返回 true,否则必须返回 false。我们在这里所做的是使用request()Laravel 提供的辅助函数并获取我们从表单中引用的字段的值input($this->referredField)

public function passes($attribute, $value){
        return request()->input($this->referredField) === $value;
}
Run Code Online (Sandbox Code Playgroud)

我们可以在此函数中编辑验证失败时创建的错误消息。

public function message(){
        return 'The :attribute must match with' . $this->referredField . '.';
}
Run Code Online (Sandbox Code Playgroud)

然后,我们将自定义 Rule 类实例化为一个对象,用作验证规则,如下代码所示。 'confirm-new-pass' => ['required', 'string', 'max:100', new StrEqualTo('new-pass')]

希望这可以帮助!!!


Ake*_*rts 3

因为是正在使用的对象$validator的完整实例,所以我们可以使用以下方法从中检索数据:ValidatorgetData()

public function validate($attribute, $value, $parameters, $validator)
{
    // You may want to check to make sure this exists first.
    $otherField = $parameters[0];

    $otherValue = data_get($validator->getData(), $otherField);

    // @todo Validate $otherValue
}
Run Code Online (Sandbox Code Playgroud)

使用data_get()还允许您对嵌套数组值使用点表示法。