Search code examples
phplaravelphp-carbonlaravel-validation

Carbon\Exceptions\InvalidFormatException Unexpected data found. Unexpected data found. Trailing data, error on laravel date format validation


In my laravel based application, when updating user accounts I'm trying to validate the birthday field. I have the following in my controller's update method

$rules = [
    'date_of_birth'=>[
        'required',
        'date',
        'date_format:Y-m-d',
        function ($attribute, $value, $fail) {
            $age = Carbon::createFromFormat('Y-m-d', $value)->diff(Carbon::now())->y;
            if($age < 18 || $age > 70) {
                $fail('Âge invalide. l\'âge devrait être 18-70');
            }
        },
    ]
];

So the date format has to be Y-m-d and the age range has to be between 18-70.

Following is my form field

<div class="col-md-6 ">
 {!! Form::text('date_of_birth', old('date_of_birth', $user->date_of_birth), array('placeholder' => 'Date of birth','class' => 'form-control txt_txt','id'=>'datepicker')) !!}
 <span toggle="#dob-field" class="fa fa-fw fa-calendar field-icon toggle-dob"></span>
 {!! $errors->first('date_of_birth', '<span class="help-block" role="alert">:message</span>') !!}
 </div>

But whenever I tried to submit an invalid date format like, 18/12/1995, it kept giving me following error...

Carbon\Exceptions\InvalidFormatException
Unexpected data found. Unexpected data found. Trailing data 

How can I fix this and validate the date format and display the error message properly.


Solution

  • It's checking all of the validation rules at the same time, which means even if Y-m-d fails, it's still going to check your age limit. Add bail to your validation rules so that it will stop validation on the first failure.

    'date_of_birth'=>['bail', 'required','date', 'date_format:Y-m-d', function ($attribute, $value, $fail) {