php Laravel 5.1 date_format 验证允许两种格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32006092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:45:12  来源:igfitidea点击:

Laravel 5.1 date_format validation allow two formats

phplaravellaravel-5date-format

提问by karmendra

I use following date validation for incoming POST request.

我对传入的 POST 请求使用以下日期验证。

'trep_txn_date' => 'date_format:"Y-m-d H:i:s.u"'

This will only allow a date of this kind i.e. 2012-01-21 15:59:44.8

这将只允许此类日期,即 2012-01-21 15:59:44.8

I also want to allow date without the TIME e.g. 2012-01-21, which when sent to mysql db will automatically store as 2012-01-21 00:00:00.0

我还想允许没有 TIME 的日期,例如 2012-01-21,当发送到 mysql db 时,它会自动存储为 2012-01-21 00:00:00.0

Is there a way I can do this using a Laravel's existing validation rules. Is there a way to define multiple formats in date_format rule something like below.

有没有办法使用 Laravel 现有的验证规则来做到这一点。有没有办法在 date_format 规则中定义多种格式,如下所示。

'trep_txn_date' => 'date_format:"Y-m-d H:i:s.u","Y-m-d"' //btw this didn't work.

Thanks,

谢谢,

K

回答by jedrzej.kurylo

The date_formatvalidator takes only one date format as parameter. In order to be able to use multiple formats, you'll need to build a custom validation rule. Luckily, it's pretty simple.

DATE_FORMAT验证只需要一个日期格式参数。为了能够使用多种格式,您需要构建自定义验证规则。幸运的是,这很简单。

You can define the multi-format date validation in your AppServiceProviderwith the following code:

您可以使用以下代码在AppServiceProvider 中定义多格式日期验证:

class AppServiceProvider extends ServiceProvider  
{
  public function boot()
  {
    Validator::extend('date_multi_format', function($attribute, $value, $formats) {
      // iterate through all formats
      foreach($formats as $format) {

        // parse date with current format
        $parsed = date_parse_from_format($format, $value);

        // if value matches given format return true=validation succeeded 
        if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
          return true;
        }
      }

      // value did not match any of the provided formats, so return false=validation failed
      return false;
    });
  }
}

You can later use this new validation rule like that:

您稍后可以像这样使用这个新的验证规则:

'trep_txn_date' => 'date_multi_format:"Y-m-d H:i:s.u","Y-m-d"' 

You can read more about how to create custom validation rules here: http://laravel.com/docs/5.1/validation#custom-validation-rules

您可以在此处阅读有关如何创建自定义验证规则的更多信息:http: //laravel.com/docs/5.1/validation#custom-validation-rules