【问题标题】:Laravel Validation: How to access rules of an attribute in customized validationLaravel 验证:如何在自定义验证中访问属性的规则
【发布时间】:2015-11-09 12:15:40
【问题描述】:

在下面的规则中,我有我的自定义验证customRule: *date*

$rules = [
  'my_date' => 'required|date_format: Y-m-d|customRule: someDate',
];

在我的自定义验证规则扩展中,我需要访问规则的date_format 属性:

Validator::extend('customRule', function($attribute, $value, $parameters) {

   $format = $attribute->getRules()['date_format']; // I need something like this 

   return $format == 'Y-m-d';
});

如何获取扩展验证器上某个属性的规则值?

【问题讨论】:

    标签: php validation laravel laravel-5


    【解决方案1】:

    您无法访问其他规则。验证器是独立的单元——他们应该使用的唯一数据是:

    • 正在验证的字段值
    • 作为参数传递给此验证规则的值
    • 正在验证的对象的其他属性的值

    您似乎需要一个自定义验证器来包装 date_formatcustomRule 所做的事情:

    Validator::extend('custom_date_format', function($attribute, $value, $parameters) {
      $format = $parameters[0];
      $someDate = $parameters[1];
    
      $validator = Validator::make(['value' => $value], ['value' => 'date_format:' . $format]);
    
      //validate dateformat
      if ($validator->fails()) {
        return false;
      }
    
      //validate custom rule using $format and $someDate and return true if passes
    });
    

    一旦你有了它,你就可以这样使用它:

    $rules = [
      'my_date' => 'required|custom_date_format:Y-m-d,someDate',
    ];
    

    【讨论】:

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