【问题标题】:Value of datetime input field can not pass validation日期时间输入字段的值无法通过验证
【发布时间】:2018-11-03 06:55:42
【问题描述】:

我有这个用于选择日期和时间的输入字段

<input type="datetime-local" class="form-control" id="game-date-time-text" name="game_date_time">

我正在尝试使用以下规则对其进行格式化

'game_date_time' => 'required|date_format:Y-m-dTH:i'

当我查看请求中该字段的值时,示例值如下所示

2001-03-13T13:30

我尝试了各种类型的日期时间格式,包括上述一种,但我的输入值无法通过验证。这里有什么问题?

任何帮助将不胜感激。

【问题讨论】:

    标签: php laravel validation laravel-5 laravel-5.6


    【解决方案1】:

    试试这个

    'game_date_time' => 'required|date_format:"Y-m-dTH:i"'
    

    date_format 格式必须在双引号内""

    【讨论】:

      【解决方案2】:

      您需要将data_format 规则放在双引号内。

      'game_date_time' =&gt; 'required|date_format:"Y-m-dH:i"'

      在此处阅读更多信息:https://laravel.com/docs/5.6/validation#rule-date-format

      【讨论】:

      • Y-m-dH:i 不是 Y-m-dTH:i 你试过了吗?
      • 是的,我完全按照你的回答做了。
      • 在您的 'config/app.php` 中,您会发现 'timezone' =&gt; 它设置为什么? UTC?将其更改为您的区域格式。示例America/Chicago 然后清除缓存php artisan config:cache php artisan cache:clear
      【解决方案3】:

      我试过了,效果很好。

      'game_date_time' => 'required|date_format:"Y-m-d\TH:i"'
      

      【讨论】:

        【解决方案4】:

        好的,我想我找到了解决方案。首先,确保您的日期列是DATETIME 类型。假设您在模型中的 date_time 规则是这样的:

        public static $date_rules = [
            'game_date_time' => 'required|date_format:Y-m-dTH:i'
        ];
        

        在您的控制器中,您获取 date_time 值的方法:

        use Illuminate\Support\Facades\Validator;
        
        public function postDate(Request $request, Role $role){
        
            $datevalidator = Validator::make($request->all(), YourModel::$date_rules);
            if ($datevalidator->fails()){
                return Redirect::back()->withErrors($datevalidator)->withInput();
            }// this 'if' checks the validation.
            $game_date_time=$request->get('game_date_time');
            return $game_date_time;
        }
        

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-21
          • 1970-01-01
          • 1970-01-01
          • 2018-02-24
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 2015-10-17
          相关资源
          最近更新 更多