【问题标题】:Laravel : Group existing validation rules in single custom Rule?Laravel:在单个自定义规则中分组现有的验证规则?
【发布时间】:2019-03-17 14:23:41
【问题描述】:

是否可以在自定义规则中使用现有的 Laravel 验证规则?

示例:required|string|max:100 我只想将这些规则归为一条规则custom_rule_name

不管怎样

Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'required|string|max:100';//something like this
});

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value == 'required|string|max:100';//something like this
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

如果有可能,请告诉我?

谢谢,

卡莱姆

【问题讨论】:

    标签: php laravel laravel-5 laravel-validation


    【解决方案1】:

    不,正确的做法是在验证请求时选择每个规则,而不是创建一个包含所有逻辑的规则。

    【讨论】:

      【解决方案2】:

      您可以在passes() 函数中使用Validator 外观。像这样:

      <?php
      
      namespace App\Rules;
      
      use Illuminate\Contracts\Validation\Rule;
      use Illuminate\Support\Facades\Validator;
      
      class Uppercase implements Rule
      {
          /**
           * Determine if the validation rule passes.
           *
           * @param  string  $attribute
           * @param  mixed  $value
           * @return bool
           */
          public function passes($attribute, $value)
          {
              $validator = Validator::make([$attribute => $value], [
                  $attribute => 'required|string|max:100',
              ]);
      
              return !$validator->fails();
          }
      
          /**
           * Get the validation error message.
           *
           * @return string
           */
          public function message()
          {
              return 'The :attribute must be uppercase.';
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-11
        • 2018-02-18
        • 2017-12-01
        • 2019-02-12
        • 2016-11-22
        • 2015-06-14
        • 2015-01-26
        • 2016-01-13
        • 2017-12-06
        相关资源
        最近更新 更多