使用laravel验证规则检查用户的年龄 [英] Check user's age with laravel validation rules
问题描述
如何在注册时检查用户的年龄?我希望将最低年龄设置为13岁.我询问用户的出生日期,当我验证其他凭据时,我想检查一下它们是否确实是13岁以上.
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'
];
如何检查输入的日期是13年前或更早?
How can I check that the date entered is 13 years ago or more?
我发现我可以使用 Laravel文档中的before:yyy-mm-dd
规则,就像这样:
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'
];
- 如何计算值?
- 如何在规则中使用该值?
推荐答案
RMcLeod的答案还可以,但是我建议您将其提取为自定义规则:
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
这篇关于使用laravel验证规则检查用户的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!