Validate if age is over 18 years old

前端 未结 6 2337
情歌与酒
情歌与酒 2020-12-14 12:23

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 =          


        
6条回答
  •  一整个雨季
    2020-12-14 13:10

    Why not? The only problem to me, is the User Interface - how you send out the error message elegantly to the user.

    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'); 
        }
    }
    

    Or you can:

    // 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;
    }
    

提交回复
热议问题