【问题标题】:minimum Age validation laravel最小年龄验证 laravel
【发布时间】:2017-12-06 17:45:30
【问题描述】:

我想验证用户信息,例如出生日期,因为我在验证中使用了以下语句,但是我如何使其动态化,以便用户最小年龄可能为 13 岁。低于不能注册?

  return Validator::make($data, [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'date_of_birth' =>'required|date|before:2011-06-08',
        ]);

【问题讨论】:

  • 当你这样写日期2011-06-08时它是否有效?

标签: php laravel laravel-5


【解决方案1】:

根据https://laravel.com/docs/5.5/validation 的文档,您应该能够使用与 strtotime() 函数一起使用的任何有效字符串。在这种情况下, strtotime('13 years ago') 是您所追求的动态日期的有效描述符。因此,以下应该有效:

return Validator::make($data, [
    'first_name' => 'required|string|max:255',
    'last_name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:users',
    'password' => 'required|string|min:6',
    'date_of_birth' =>'required|date|before:13 years ago',
]);

【讨论】:

    【解决方案2】:

    您可以像这样使用 Carbon:

    return Validator::make($data, [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'date_of_birth' =>'required|date|before:'.Carbon::now()->subYears(13),
        ]);
    

    Ps : 不要忘记添加导入 use Carbon\Carbon;

    【讨论】:

      【解决方案3】:

      要检查用户的年龄至少为 13 岁,请使用 after 规则。将 date_of_birth 的规则更改为

      'date_of_birth' =>'required|date|after:13 years',
      

      before 将不起作用,因为它与 after 相反

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-14
        • 2022-07-01
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        • 2016-03-30
        • 2013-04-10
        • 2014-08-23
        相关资源
        最近更新 更多