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'
];
- How do I calculate the value?
- How do I use that value within the rules?
You can use Carbon which comes with laravel
A simple way to check that the date is greater(older) than N years is to set the
before
rule to minus N years.This is a bit old, but I want to share the way I do it.
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. Withbefore_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.RMcLeod answer is OK, but I'd suggest you extracting this as a custom rule:
This way you can use the rule for any age you like: