Home > Net >  Carbon\Exceptions\InvalidFormatException issue in laravel when trying to sore the date
Carbon\Exceptions\InvalidFormatException issue in laravel when trying to sore the date

Time:09-28

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

'date_of_birth'=>['required','date_format:m/d/Y',function ($attribute, $value, $fail) {
        
        $age=Carbon::parse($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 m/d/Y 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', null, array('placeholder' =>  __('texts.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>

Now, whenever I put a date with an invalid date format like 18/12/1993, it kept giving me an error saying,

Carbon\Exceptions\InvalidFormatException
Could not parse '18/12/1993': DateTime::__construct(): Failed to parse time string (18/12/1993) at position 0 (1): Unexpected character 

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

CodePudding user response:

Please change your code from

$age=Carbon::parse($value)->diff(Carbon::now())->y;

to

$age=Carbon::createFromFormat('d/m/Y', $value)->diff(Carbon::now())->y;
  • Related