我正在使用Laravel网络应用程序,该应用程序运行良好。我对此有些陌生,希望添加一项功能,Larvel可以验证用户输入的日期,并确保该日期已超过18年。如果不是这样,则会在前端向用户抛出错误。.请协助?
表单的前端部分
<form method="POST" action="{{ route('b2c.getplans') }}" id="travel_form" accept-charset="UTF-8">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group {{ $errors->has('dob') ? ' has-error' : '' }}">
<input type="date" class="form-input" name="dob" value="{{ old('dob') }}" required>
<label>Date of Birth *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
@if ($errors->has('dob'))
<span class="help-block">
<strong>{{ $errors->first('dob') }}</strong>
</span>
@endif
</div>
<button type="submit" style="cursor:pointer;"> Get Plans</button>
</form>
控制器
//Post Request of plan entries
public
function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'dob' => 'required'
]);
}
路线
Route::post( '/getplans', 'B2CController@validatePlanEntries')->name('b2c.getplans');
答案 0 :(得分:0)
在$.getJSON("data.json", function(data) {
函数的AppServiceProvider
中放置此自定义验证。
AppServiceProvider
boot()
控制器
public function boot()
{
Validator::extend('valid_birth_date', function ($attribute, $value, $parameters, $validator){
$date_different = date_diff(new \DateTime($value), new \DateTime())->y;
return $date_different >= 18;
});
}
答案 1 :(得分:0)
您可以创建针对该年龄的自定义验证器,也许这会给您一个想法:
$validation = $this->validate($request, [
'dob' => [
'required',
function ($attribute, $value, $fail) {
$now = Carbon::now();
$userDob = Carbon::parse($value);
if ($userDob->diffInYears($now) <= 18) {
$fail('You are less than 18 years old');
}
},
]
]);