Search code examples
laravellaravel-8laravel-validation

Laravel date_format validation failing for HTML input type week


I got this data from request:

{
    "type": "custom",
    "start_week": "2020-W19"
}

And my validation rules are:

    return [
        'type' => 'required|in:standard,custom',
        'start_week' => 'required|date_format:Y-\WW',
    ];

Which gives me this result:

"errors": {
    "start_week": [
        "The start week does not match the format Y-\\WW."
    ]
}

I used this format before for validating week type input like "2020-W19".

Am I doing something wrong, what can I do?


Solution

  • I tried it. You'r right. Surprisingly it doesn't work.

    But here is a way that you can deal with it. By Using Closures and Carbon instance directly we can have our own custom rule which works fine:

    $request->validate([
        'start_week' => [
            'required',
            function ($attribute, $value, $fail) {
                if (!Carbon\Carbon::hasFormat($value, 'Y-\WW')) {
                    $fail('The '.$attribute.' is invalid.');
                }
            },
        ]
    ]);
    

    More info : Doc