年龄验证PHP

时间:2013-09-14 00:25:45

标签: php html select option

我正在使用一个非常有效的脚本来验证我正在处理的网站的年龄。目前,它使用下拉菜单选择月,日,年。我希望可以更改下拉菜单,让用户输入月,日,年。

以下是代码:

                <?php

            define('MIN_AGE', 21); // Enter the minimum age that your website visitors must be to view your content (replace 18 with your number)
            define('COOKIE_DAYS', 30); //Enter the number of days you would like the cookie to last (replace 30 with your number)

            // BE CAREFUL EDITING ANYTHING BELOW THIS LINE //

            date_default_timezone_set('America/Los_Angeles');
            function get_birth_drops($year = '', $month = '', $day = '')
            {
                $out = '';

                $year = $year ? $year : '';
                $month = $month ? $month : '';
                $day = $day ? $day : '';

                $month_select = '<label>MM: <select name="bmonth" id="bmonth"><option value=""></option>';
                for($i = 1; $i <=12; $i ++)
                {
                    $selected = ($i == $month) ? ' selected':'';
                    $month_select .= '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
                }
                $month_select .= '</select></label>';

                $day_select = ' <label>DD: <select name="bday" id="bday"><option value=""></option>';
                for($i = 1; $i <=31; $i ++)
                {
                    $selected = ($i == $day) ? ' selected':'';
                    $day_select .= '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
                }
                $day_select .= '</select></label>';

                $year_select = ' <label>YYYY: <select name="byear" id="byear"><option value=""></option>';
                for($i = 2010; $i >= 1950; $i --)
                {
                    $selected = ($i == $year) ? ' selected':'';
                    $year_select .= '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
                }
                $year_select .= '</select></label>';

                $out = $month_select . $day_select . $year_select;

                return $out;
            }

            function calculateAge($birthday){
                return floor((time() - strtotime($birthday))/31556926);
            }
            ?>

有什么想法?万分感谢!

2 个答案:

答案 0 :(得分:0)

您应该使用文本输入字段:

//Month input field instead of select field
$month_select = '<label>MM: <input type="text" name="bmonth" id="bmonth" value="' . $month . '" /></label>';

答案 1 :(得分:0)

目前,函数get_birth_drops输出三个字段作为选择元素。要将它们更改为文本输入,只需更改存储选择字段html的变量:

示例:

$month_select = '<label>MM: <input type="number" name="bmonth" id="bmonth" /><label>';

但是,这不会验证数据,因此您可能希望包含一些JavaScript来处理它。验证也可以使用HTML5完成:

示例:

$month_select = '<label>MM: <input type="number" min="1" max="31" name="bmonth" id="bmonth" /><label>'

希望有所帮助。