【问题标题】:Is there a way to use parameters in custom \Illuminate\Contracts\Validation\Rule有没有办法在自定义 \Illuminate\Contracts\Validation\Rule 中使用参数
【发布时间】:2018-07-03 13:31:26
【问题描述】:

在 Laravel 中使用 write custom validation rule 的一种方法是调用 Artisan 方法 make:rule

php artisan make:rule EmptyIf

那我就不知道怎么处理参数了。 “参数”的意思类似于require_if:foo,bar\Illuminate\Contracts\Validation\Rule 接口对于 passes 函数只有两个参数:

public function passes($attribute, $value);

所以我不明白应该在哪里添加参数。我知道我可以通过服务提供者扩展验证器,就像这样:

Validator::extend('foo', function ($attribute, $value, $parameters, $validator) { 
    //
});

但这似乎是一种旧方式,在我看来有点混乱。有没有办法处理Rulepasses 函数中的参数?

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.5 laravel-validation


    【解决方案1】:

    我想做这样的事情:

    protected $validationRules = [
            'name' => 'required|myRule:a,b',
    ];
    

    我从我的服务提供者 book() 方法中调用我的规则:

    Validator::extend(
        'myRule',
        function ($attribute, $value, $parameters, $validator) {
            $rule = new MyRule();
            $rule->setA($parameters[0])
                ->setB($parameters[1]);
            return $rule->passes($attribute, $value);
        },
        MyRule::errorMessage()
    );
    

    规则如下:

    use Illuminate\Contracts\Validation\Rule;
    
    /**
     * Check if an encoded image string is a valid image
     */
    class EncodedImage implements Rule
    {
        public function setA($a){}
        public function setB($b){}
    
        public function passes($attribute, $value)
        {
            return true;
        }
    
        public function message()
        {
            return self::errorMessage();
        }
    
        /**
         * Static so the ServiceProvider can read it.
         */
        public static function errorMessage()
        {
            return 'The :attribute is not valid';
        }
    }
    
    

    【讨论】:

      【解决方案2】:

      您可以为您的自定义规则定义构造函数,然后在自定义规则对象中传递您的参数。 自定义规则:

      class CustomRule implements Rule
      {
          private $params = [];
      
          public function __construct($params)
          {
              $this->params = $params;
          }    
      
          public function passes($attribute, $value)
          {
              return /*Here you can use $this->params*/;
          }
      }
      

      验证:

      $request->validate([
          'input' => ['rule', new CustomRule(['param1','param2','paramN'])],
      ]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 2023-02-03
        • 2019-11-28
        • 1970-01-01
        相关资源
        最近更新 更多