Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check user's age with laravel validation rules

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 credentials, I want to check that they are in fact 13+.

An excerpt from my User model looks like this:

$rules = [
            'name'                  => 'required|alpha|min:1',
            'email'                 => 'required|email|unique:users',
            'dob'                   => 'required|date'
         ];

How can I check that the date entered is 13 years ago or more?

I have seen that I can use the before:yyy-mm-dd rule from the Laravel Docs, like so:

$rules = [
            'name'                  => 'required|alpha|min:1',
            'email'                 => 'required|email|unique:users',
            'dob'                   => 'required|date|before:2001-04-15'
         ];
  1. How do I calculate the value?
  2. How do I use that value within the rules?
like image 337
Michael Avatar asked Apr 15 '14 10:04

Michael


3 Answers

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
];
like image 138
RMcLeod Avatar answered Oct 30 '22 13:10

RMcLeod


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',
]
like image 22
Zanshin13 Avatar answered Oct 30 '22 12:10

Zanshin13


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
like image 26
Jarek Tkaczyk Avatar answered Oct 30 '22 13:10

Jarek Tkaczyk