arun
arun

Reputation: 4815

Laravel cannot validate field against custom date format

I am having a date format like this 30 Mar, 2018.

if i apply this 'start_date' => 'required|date validation rule, then The start date is not a valid date. error message is showing.

I have this code in model:

<?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);
    }

}

For date input i am having,

<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">

Even i tried to add this date_format:d M, Y rule, it also show The start date does not match the format d M. it is not considering , and Y.

Where do i miss? whats the problem?

Upvotes: 1

Views: 1031

Answers (1)

Ivanka Todorova
Ivanka Todorova

Reputation: 10219

You can supply a custom format for validation, as you have tried:

date_format:format

However you need to escape the comma, because that's the rule parameter separator, using quotes "d M, Y"

Full rule set for your field:

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

Remember it's stated in the documentation that:

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.

Upvotes: 2

Related Questions