php 使用 Laravel 验证器验证自定义日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50287823/
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-26 02:48:29  来源:igfitidea点击:

Validating a custom date format in with laravel validator

phplaravellaravel-5

提问by jacobdo

In my app, the user selects date from a datepicker and the date is then displayed in the input in a format that corresponds user's locale.

在我的应用程序中,用户从日期选择器中选择日期,然后该日期以对应于用户语言环境的格式显示在输入中。

When the form is submitted, I would like to validate the respective date, however, the validator does not know the date format that the date was submitted in.

提交表单时,我想验证相应的日期,但是,验证器不知道提交日期的日期格式。

My question is whether I should mutate the date into Y-m-d before it is passed to validator or is there a way I can tell the Validator the right format to validate in?

我的问题是我是否应该在将日期传递给验证器之前将日期更改为 Ymd,或者有没有办法告诉验证器要验证的正确格式?

回答by Niraj Shah

The easier option is to use the Laravel date_format:formatrule (https://laravel.com/docs/5.5/validation#rule-date-format). It's a built-in function in Laravel without the need for a custom rule (available in Laravel 5.0+).

更简单的选择是使用 Laraveldate_format:format规则(https://laravel.com/docs/5.5/validation#rule-date-format)。它是 Laravel 中的内置函数,无需自定义规则(在 Laravel 5.0+ 中可用)。

You can do:

你可以做:

$rule['date'] = 'required|date_format:d/m/Y';

or

或者

$rule['date'] = 'required|date_format:Y-m-d';

回答by Saurabh

Laravel Custom Validation Rules

Laravel 自定义验证规则

You can define the multi-format date validation in your AppServiceProvider

您可以在您的 AppServiceProvider

class AppServiceProvider extends ServiceProvider  
{
  public function boot()
  {
    Validator::extend('new-format', function($attribute, $value, $formats) {

      foreach($formats as $format) {

        $parsed = date_parse_from_format($format, $value);

        // validation success
        if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
          return true;
        }
      }

      // validation failed
      return false;
    });
  }
}

Now you can use custom validation rule:

现在您可以使用自定义验证规则:

'your-date' => 'new-format:"Y-m-d H:i:s.u","Y-m-d"'

'your-date' => 'new-format:"Y-m-d H:i:s.u","Y-m-d"'