【问题标题】:laravel validate date parts constructionlaravel 验证日期部件构造
【发布时间】:2019-06-27 12:26:20
【问题描述】:

我正在尝试验证日期,但它不起作用,我正在尝试从部分重建日期,并在我的清理功能中添加要在请求中验证的值。我传入的日期是尝试抛出错误的无效日期,但我没有让它在我的请求类中工作。我输入 2020-02-30 的日期无效,因为不存在这样的日期

    $this->request->add(['event_date' => date('Y-m-d', strtotime($this->request->get('month') . '/' . $this->request->get('day') . '/' . $this->request->get('year')))]);

    $input = $this->all();

    $input['owner_firstname'] = filter_var($input['owner_firstname'], FILTER_SANITIZE_STRING);

    ....
    ....
    $this->merge($input);  


    $rules = [
        'owner_firstname'       => 'required|min:2|max:30',
        'owner_lastname'        => 'required|min:2|max:30',
        'owner_email'           => 'email',
        'owner_type'            => 'required',
        'partner_firstname'     => 'required|min:2|max:30',
        'partner_lastname'      => 'required|min:2|max:30',
        'partner_email '        => 'email',
        'partner_type'          => 'required',
        'month'                 => 'not_in:0',
        'day'                   => 'not_in:0',
        'year'                  => 'required|digits:4|integer|min:' . date('Y') . '|max:'. (date('Y', strtotime('+9 months'))),
        'event_date'            => 'date',
        'event_city'            => 'required|not_in:0',
        'event_country'         => 'required|not_in:0',
        'number_of_guests'      => 'required',
        'guests_message'        => 'required|min:30|max:5000',
    ];

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    两件事:

    1) 验证正在通过,因为您构建日期字符串以发送到验证器的方式。

    date('Y-m-d', strtotime('02/30/2020'))  // This becomes "2020-03-01"
    

    因此,由于 2020 年 3 月 1 日是有效日期,因此验证通过。相反,您可以直接用破折号构造日期字符串。

    2) 在调用$this->request->add() 时,有些情况(如AJAX 请求)不会将参数添加到调用$this->all() 时获得的结果中。尝试使用 merge() 添加参数。

    // This will set the date as '2020-02-30' and fail validation
    $this->merge(['event_date' => $this->request->get('year') . '-' . $this->request->get('month') . '-' . $this->request->get('day')]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 2020-01-14
      • 1970-01-01
      相关资源
      最近更新 更多