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

时间:2019-10-21 12:54:57

标签: laravel validation php-7 rules laravel-validation

我正在尝试创建一个接受参数的自定义验证规则,但是该参数是请求中另一个字段的名称,例如for j in range(0, 500) for i in range(0,5000): result = list_of_values[j] + i 规则。

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

目前,我正在将规则类创建为

required_with

并将其注册到我的服务提供商中

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

所以我可以在我的请求中将其用作

Validator::extend('my_rule', 'path\to\MyClassRule@validate');

我想做的是

public function rules()
{
    return [
        'field' => ['my_rule'],
    ];
}

并在我的规则类中使用public function rules() { return [ 'other_field' => [...], 'field' => ['my_rule:other_rule'], ]; } 值,但是other_field的{​​{1}}值仅为validate()。即包含其他字段名称而不是其值的数组。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

由于$validator是所使用的Validator对象的完整实例,我们可以使用getData()从其中检索数据:

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
}

使用data_get()还可以将点表示法用于嵌套数组值。

答案 1 :(得分:0)

工匠命令

php artisan make:rule ValidateOtherField

Class ValidateOtherField

class ValidateOtherField implements Rule
{
        private $error = '';
        public function passes($attribute, $value)
        {
            if(request()->has('field') && request()->get('field') === 'MyValueSuccess'){
                if(is_string($value)){
                    return true;
                } else {
                    $this->error = '- not valid field';
                }
            }
            return false;
        }
        public function message()
        {
            return "Error :attribute {$this->error}";
        }
 }

规则

public function rules()
{
    return [
        'field'       => ['string'], //Validate field
        'other_field' => [new ValidateOtherField],        
    ];
}

答案 2 :(得分:0)

我正在Laravel 7.x中运行它。

以我为例,我试图制定一条规则来比较表单中的两个字段是否彼此相等。

按照Laravel文档中的说明创建一个新的Rule Object。
https://laravel.com/docs/7.x/validation#custom-validation-rules


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

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

<?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 . '.';
    }
}

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

private $referredField = null;

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

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

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

我们可以在下面的此功能中编辑验证失败时将创建的错误消息。

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

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

希望这会有所帮助!