验证年龄是否超过18岁 [英] Validate if age is over 18 years old
问题描述
想知道,我是否可以这样做来验证用户输入的日期超过18?
Just wondering, can I do this to validate that a user has entered a date over 18?
//Validate for users over 18 only
function time($then, $min)
{
$then = strtotime('March 23, 1988');
//The age to be over, over +18
$min = strtotime('+18 years', $then);
echo $min;
if (time() < $min) {
die('Not 18');
}
}
偶然发现了这个函数date_diff: http://www.php.net/manual/en/function. date-diff.php 看起来,甚至更有希望.
Just stumbled across this function date_diff: http://www.php.net/manual/en/function.date-diff.php Looks, even more promising.
推荐答案
为什么不呢?对我来说,唯一的问题是用户界面-如何将错误消息优雅地发送给用户.
Why not? The only problem to me, is the User Interface - how you send out the error message elegantly to the user.
另一方面,由于您的生日不正确(您使用固定的生日),因此您的功能可能无法正常使用.您应该将"1988年3月23日"更改为$ then
On another note, your function might not work properly as you did not intake a proper birthday (you are using a fixed birthday). You should change 'March 23, 1988' to $then
//Validate for users over 18 only
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
//The age to be over, over +18
$min = strtotime('+18 years', $then);
echo $min;
if(time() < $min) {
die('Not 18');
}
}
或者您可以:
// validate birthday
function validateAge($birthday, $age = 18)
{
// $birthday can be UNIX_TIMESTAMP or just a string-date.
if(is_string($birthday)) {
$birthday = strtotime($birthday);
}
// check
// 31536000 is the number of seconds in a 365 days year.
if(time() - $birthday < $age * 31536000) {
return false;
}
return true;
}
这篇关于验证年龄是否超过18岁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!