Question

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?
Was it helpful?

Solution 3

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

OTHER TIPS

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',
]

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
];

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.

I have Implement This & Successfully Work You Can Use

before:'.now()->subYears(18)->toDateString()

            $validator = Validator::make($request->all(), [
                
                'birthdate' => 'required|date|before:'.now()->subYears(18)->toDateString(),
                
            ], [
                'birthdate.before' => trans('18 year validation'),                
            ]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top