【问题标题】:Validating Arrays And passing field values between each other验证数组并在彼此之间传递字段值
【发布时间】:2018-07-05 01:54:25
【问题描述】:

我正在尝试从我的表单输入中验证一个数组。我需要将我的字段值之一传递给该附加字段的规则列表中的附加表单字段的自定义规则类。这如何实现?

这里有进一步的解释。验证 field1 后,我需要将该值传递给 field2 字段 CustomRule 类。

public function rules()
{
    return [
        'array' => ['array'],
        'array.*.field1'   => [
            'required',
            'integer',
            'min:1',
            'distinct',
        ],
        'array.*.field2' => [
            'required',
            'integer',
            'min:1',
            new CustomRule(),
        ],
    ];
}

【问题讨论】:

    标签: laravel


    【解决方案1】:

    使用验证扩展会起作用:

    // register the rule in AppServiceProvider.php
    Validator::extend('custom_rule', function ($attribute, $value, $parameters, $validator) {
        // field1 is accessible in $parameters. Add your custom validation logic here, for example:
        return $value < $parameters[0];
    });
    

    然后将field1的值作为参数传递给规则:

    public function rules()
    {
        $rules = [
            'array' => ['array'],
            'array.*.field1'   => [
                'required',
                'integer',
                'min:1',
                'distinct',
            ]
        ];
    
        foreach ($this->array as $idx => $val) {
             $rules['array.' . $idx . '.field2'] = [
                'required',
                'integer',
                'min:1',
                'custom_rule:' . $val['field1'],    
             ];
        }
    
        return $rules;
    }
    

    使用规则对象:

    class CustomRule implements Rule
    {
        public $field1;
    
        public function __construct($field1)
        {
            $this->field1 = $field1;
        }
    
        /**
         * Determine if the validation rule passes.
         *
         * @param  string  $attribute
         * @param  mixed  $value
         * @return bool
         */
        public function passes($attribute, $value)
        {
            return $value < $this->field1;
        }
    
        /**
         * Get the validation error message.
         *
         * @return string
         */
        public function message()
        {
            return 'The :attribute must be less than field1.';
        }
    }
    
    // loop the array elements
    foreach ($this->array as $idx => $val) {
        $rules['array.' . $idx . '.field2'] = [
            'required',
            'integer',
            'min:1',
            new CustomRule($val['field1']),    
         ];
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-01
      • 2023-04-08
      • 1970-01-01
      • 2015-10-17
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      相关资源
      最近更新 更多