【问题标题】:Custom multi attributes in validation验证中的自定义多属性
【发布时间】:2019-07-10 21:24:14
【问题描述】:

我在 Laravel 的请求中使用验证。我想根据另一个属性的划分来处理一个属性。怎么可能控制?

    public function rules()
    {
       return [
               'number' => 'required|numeric',
               'threshold' =>['numeric',
                  function ($attribute, $value, $fail) {
                   if ($attribute > 'number/2') { 
                      $fail(('threshold must be smaller than division of number'));
                        } 
                    }, ]
                ];
    }

【问题讨论】:

    标签: laravel validation request attributes


    【解决方案1】:

    您可以在整个应用程序中全局使用request() 函数, 因此,在这种情况下,为了访问特定属性,您可以使用

    $attribute_value = request()->YOUR_ATTRIBUTE;
    

    【讨论】:

      【解决方案2】:

      只需使用 Laravel 中现在可用的 prepareForValidation 方法添加另一种方法:

      在你的Request 类中:

      <?php
      /**
       * Modify the input values
       *
       * @return void
       */
      protected function prepareForValidation(){
      
          $this->merge[
              'number_division_by_2' => $this->input('number') / 2
          ];
      }
      

      然后在你的相同Request类的规则中,你可以添加:

      <?php 
      
      public function rules()
      {
         return [
                 'number' => 'required|numeric',
                 'threshold' =>'numeric',
                 'number_division_by_2' => 'lt:threshold'
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多