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