Carbon\Exceptions\InvalidFormatException 问题 laravel 试图破坏日期

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

在我基于 laravel 的应用程序中,在创建新用户帐户时,我试图验证生日字段。我的控制器的存储方法中有以下内容

'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');
        }
    },]

所以日期格式必须是 m/d/Y 并且年龄范围必须在 18-70 之间。

以下是我的表单字段

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

现在,每当我使用无效日期格式(如 18/12/1993)输入日期时,它总是给我一个错误提示,

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 

如何解决此问题并验证日期格式并正确显示错误消息。

请从

更改您的代码
$age=Carbon::parse($value)->diff(Carbon::now())->y;

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