【问题标题】:Laravel 5.6: The values under comparison must be of the same typeLaravel 5.6:比较的值必须是相同的类型
【发布时间】:2021-04-19 11:56:43
【问题描述】:

我们最近将 Laravel 从 5.5 升级到 5.6 我有验证规则:

return [
            'min_price' => ['numeric', 'nullable', 'min:0'],
            'max_price' => ['numeric', 'nullable', 'min:0', 'gt:min_price'],
]

如果是的话会抛出错误

  1. min_price = null,max_price = 100
  2. min_price = 0, max_price = 99.99
  3. min_price = 12.50,max_price = 100
  4. min_price = 12.50,max_price = null 它说:
ERROR: The values under comparison must be of the same type "exception":"[object] (InvalidArgumentException(code: 0): The values under comparison must be of the same type at vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php:1659)
[stacktrace]
#0 vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php(849): Illuminate\\Validation\\Validator->requireSameType(12.50, 100)

它说,两个字段应该具有相同的类型,因此它不能比较整数和浮点数,也不能忽略可为空的字段。 问题在于方法validateGtvalidateLtvalidateGtevalidateLte 在特征ValidatesAttributes 中。有什么方法可以扩展或覆盖该特征吗?

【问题讨论】:

    标签: php validation comparison numeric laravel-5.6


    【解决方案1】:

    由于没有明显的解决方案,我决定创建自己的验证器并且不使用 Laravel 提供的验证器:

    class ServiceProvider extends BaseServiceProvider
    {
        public function boot()
        {
            ValidatorFacade::extend('greater_than', Validator::class.'@validateGreaterThan');
            ValidatorFacade::replacer('greater_than', function ($message, $a, $b, $parameters) {
                $attributes = trans('validation.attributes');
                $other = $parameters[0];
                $other = isset($attributes[$other]) ? $attributes[$other] : $other;
    
                return str_replace(':field', $other, $message);
            });
        }
    
        public function register()
        {
        }
    }
    

    并在这样的验证规则中使用它

    return [
                'min_price' => ['numeric', 'nullable', 'min:0'],
                'max_price' => ['numeric', 'nullable', 'min:0', 'greater_than:min_price'],
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-20
      • 2019-08-18
      • 2016-03-08
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      相关资源
      最近更新 更多