Laravel 5.1 date_format validation allow two formats

后端 未结 1 1717
情歌与酒
情歌与酒 2020-12-03 10:38

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

相关标签:
1条回答
  • 2020-12-03 11:24

    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

    0 讨论(0)
提交回复
热议问题