Check user's age with laravel validation rules

后端 未结 4 1563
刺人心
刺人心 2020-12-06 12:55

How can I check the age of a user upon registration? I want to set the minimum age to be 13 years old. I ask for the user\'s date of birth and when I validate the other cred

相关标签:
4条回答
  • 2020-12-06 13:14

    A simple way to check that the date is greater(older) than N years is to set the before rule to minus N years.

    $rules = [
        'dob' => 'required|date|before:-13 years',
    ]
    
    0 讨论(0)
  • 2020-12-06 13:21

    This is a bit old, but I want to share the way I do it.

     public function rules()
    {
        return 
        [
            ...
            'age' => 'required|date|before_or_equal:'.\Carbon\Carbon::now()->subYears(18)->format('Y-m-d'),
            ...
        ];
    }
    

    Using before is nice but it's a bit ugly for the end user, because if today it's his birthday, he won't be able to pass. With before_or_equal you get the perfect behaviour. A way to improve this would be checking the timezone with Carbon if you target a worldwide audience.

    0 讨论(0)
  • 2020-12-06 13:24

    You can use Carbon which comes with laravel

    $dt = new Carbon\Carbon();
    $before = $dt->subYears(13)->format('Y-m-d');
    
    $rules = [
        ...
        'dob' => 'required|date|before:' . $before
    ];
    
    0 讨论(0)
  • 2020-12-06 13:26

    RMcLeod answer is OK, but I'd suggest you extracting this as a custom rule:

    Validator::extend('olderThan', function($attribute, $value, $parameters)
    {
        $minAge = ( ! empty($parameters)) ? (int) $parameters[0] : 13;
        return (new DateTime)->diff(new DateTime($value))->y >= $minAge;
    
        // or the same using Carbon:
        // return Carbon\Carbon::now()->diff(new Carbon\Carbon($value))->y >= $minAge;
    });
    

    This way you can use the rule for any age you like:

    $rules = ['dob' => 'olderThan']; // checks for 13 years as a default age
    $rules = ['dob' => 'olderThan:15']; // checks for 15 years etc
    
    0 讨论(0)
提交回复
热议问题