沃梦达 / 编程问答 / php问题 / 正文

Laravel 5.1 date_format 验证允许两种格式

Laravel 5.1 date_format validation allow two formats(Laravel 5.1 date_format 验证允许两种格式)

本文介绍了Laravel 5.1 date_format 验证允许两种格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use following date validation for incoming POST request.

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

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

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

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

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

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

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.

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

谢谢,

K

推荐答案

date_format 验证器仅采用一种日期格式作为参数.为了能够使用多种格式,您需要构建自定义验证规则.幸运的是,这很简单.

The date_format validator 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.

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

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

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"' 

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

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

这篇关于Laravel 5.1 date_format 验证允许两种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 5.1 date_format 验证允许两种格式

基础教程推荐