在我基于 laravel 的應用程式中,創建新用戶帳戶時,我試圖驗證生日欄位。我的控制器的 store 方法中有以下內容
'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\'age 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 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
如何解決此問題并驗證日期格式并正確顯示錯誤訊息。
uj5u.com熱心網友回復:
請更改您的代碼
$age=Carbon::parse($value)->diff(Carbon::now())->y;
到
$age=Carbon::createFromFormat('d/m/Y', $value)->diff(Carbon::now())->y;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324126.html
