Laravel 无法根据自定义日期格式验证字段

Laravel cannot validate field against custom date format

我有这样的日期格式 30 Mar, 2018

如果我应用此 'start_date' => 'required|date 验证规则,则会显示 The start date is not a valid date. 错误消息。

我在模型中有这个代码:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Rates extends Model
{
    protected $guarded = ['id'];

    //protected $dateFormat = 'Y-m-d H:i:s';

    protected $dates = [
        'start_date',
        'end_date'
    ];


    public function setStartDateAttribute($value)
    {
        $this->attributes['start_date'] = Carbon::createFromFormat('d M, Y',$value);
    }

    public function setEndDateAttribute($value)
    {
        $this->attributes['end_date'] = Carbon::createFromFormat('d M, Y',$value);
    }

}

对于我的日期输入,

<input class="form-control form_datetime_start valid" placeholder="Enter Start Date" name="start_date" type="text" value="30 Mar, 2018" aria-required="true" aria-invalid="false">

即使我尝试添加这个 date_format:d M, Y 规则,它也显示 The start date does not match the format d M. 它没有考虑 ,Y.

我错过了什么地方?有什么问题吗?

您可以提供自定义格式进行验证,如您所试:

date_format:format

但是你需要转义逗号,因为这是规则参数分隔符,使用引号 "d M, Y"

您的领域的完整规则集:

'start_date' => 'required|date_format:"d M, Y"'

请记住,documentation 中指出:

date_format:format

The field under validation must match the given format. You should use either date or date_format when validating a field, not both.