Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

php - Laravel 5.1 date_format validation allow two formats

I use following date validation for incoming POST request.

'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

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

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.

Thanks,

K

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...