【问题标题】:Using datepicker to check the age of users over 18 years使用 datepicker 检查 18 岁以上用户的年龄
【发布时间】:2019-03-14 01:31:15
【问题描述】:

我正在开发一个运行良好的 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');

【问题讨论】:

    标签: laravel validation date


    【解决方案1】:

    AppServiceProvider 函数中的boot() 中放置此自定义验证。

    AppServiceProvider

    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;
        });
    }
    

    控制器

    $validation = $this->validate($request, [
        'dob' => 'required|valid_birth_date'
    ],[
        'dob.valid_birth_date' => 'your custom message'
    ]);
    

    【讨论】:

    • ,, 感谢您的帮助,, 我收到以下错误AppServiceProvider.php 第 47 行 当我实现它时.. 是导入 Validator 类的问题吗?其次,我正在使用 Lravel 5.4 版,与您的解决方案一起工作〜谢谢...
    • 我不能把这个方法放在boot() 函数中。是这个问题吗?
    • 好的,请注意,现在可以正常工作了,如果我想添加自定义错误消息以在验证失败时显示给用户
    • 最后它就像一个魅力,,,非常感谢 Tharaka
    【解决方案2】:

    您可以为年龄创建自定义验证器,也许这会给您一个想法: $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'); } }, ] ]);

    【讨论】:

    • 确保也包含=。因为 18 年也是有效的。
    猜你喜欢
    • 1970-01-01
    • 2016-12-02
    • 2022-01-22
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多