我对收到的POST请求使用以下日期验证.

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

这将只允许此类日期,即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

有没有一种方法可以使用Laravel现有的验证规则来实现这一点.

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

Thanks,

K

推荐答案

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中定义多格式日期验证:

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

Laravel相关问答推荐

灯丝:设定模式标题

如何使用 Laravel 进行继承

如何在 Laravel 9 中获取带分页的订单列表?

Laravel 5 如何配置 Queue 数据库驱动程序以连接到非默认数据库?

RuntimeException 未安装 Zip PHP 扩展

如何在 Laravel 中使用内存数据库的完整测试套件之前迁移和 seeder ?

Laravel 5 如何全局设置 Cache-Control HTTP 标头?

.gitignore 不忽略文件夹

在 laravel 如何将额外的数据传递给 mutators 和 accessors

如何使用 Laravel 模型访问数据库视图?

Laravel 4,如何测试复选框是否被选中?

如何在 laravel blade中进行一次性推送

将 Laravel Socialite 与 API 一起使用?

Laravel上传文件无法写入目录

使用 laravel eloquent 关系检索除 NULL 之外的所有记录

在 laravel 6.0 中未定义命令ui

扩展 Eloquent 的类的构造函数

防止 Eloquent 查询上的模型水合

Lumen/Laravel 6:调用未定义的函数 array_except()

如何在 Laravel 中动态更改 .env 文件中的变量?