如何使下拉列表中的第一个选项成为不可接受的答案?

时间:2013-01-05 12:05:32

标签: php html selection required-field

好的,我有一个表单,在这个表单中有一堆必填字段。此表单的生日部分包含3个字段:月,日和年。 现在我要做的就是用"月:","日:"和"年:"在下拉列表的顶部,但我不希望这些选项是可接受的答案!当我在没有选择实际的月,日和年的情况下提交表单时,应该说我打印错误时需要月,日和年!我怎么能做到这一点? 我的" if语句"使所需字段位于此代码的底部:

<form action="" method="post">  
        <ul id="register">
            <li>
                Birthday:

                <select name="month">
                    <option value="month">Month:</option>
                    <option value="January">January</option>
                    //all the other months
                </select>

                <select name="day">
                    <option value="day">Day:</option>
                    <option value="1">1</option>
                    //all the other days of the month
                </select>

                <select name="year">
                    <option value="year">Year:</option>
                    <option value="2013">2013</option>
                    //more year options
                </select><br><br>
            </li>

            <li>
                <input type="submit" name="registrationform" value="Sign up">
            </li>
        </ul>
    </form>
    <?php
    if (!empty($_POST['registrationform'])) {
    if(isset($_POST['registrationform'])){
        $required_fields = array('month', 'day', 'year');
        foreach ( $required_fields as $key=>$value) {
         if (!isset($_POST[$value]) || $_POST[$value]=='') {
              $errors[$value] = $key." is required";

            }
   }

   print_r($errors);
}
    }

    ?>

3 个答案:

答案 0 :(得分:3)

使用optgroup

<select name="month">
  <optgroup label="Month:">
    <option value="January">January</option>
    //all the other months
  </optgroup>
</select>

etc.

JSFiddle

或禁用该选项并选择标题,如果您想要显示标题 - 一旦触摸列表,标题将无法选择。

<select name="month">
    <option disabled="disabled" selected="selected">Month:</option>
    <option value="January">January</option>
    //all the other months
</select>

JSFiddle

enter image description here

答案 1 :(得分:1)

我同意PassKit,但请为您的代码添加一些验证

if (!is_int($_POST[$value])) {
  // not valid
}

并且不要将月份发布为1月份,而是将其作为1月12日发布,因为它更安全,更容易验证

答案 2 :(得分:1)

给它一个空/无值并验证它