我有以下内容在表单上生成状态下拉列表:
$states = array('State', 'Alabama', 'Alaska', 'Arizona', 'Arkansas');
echo "<select name='choose_state'>\n";
foreach ($states as $key => $state)
{echo "<option value='$key'>$state</option>\n";}
echo "</select>";
我如何确保用户确定
1)仅选择阵列中的一个选项
2)没有选择默认值? ([0] =&gt; string(5)“State”)
编辑:在php中验证,这是用于在发布到数据库之前收集用户信息的表单 我尝试使用in_array并试图排除默认值
答案 0 :(得分:1)
我认为你错过了一些支票。您永远不应该依赖于精心张贴的内容,并始终执行彻底的检查:
$chosen_state = null;
if (array_key_exists('choose_state', $_POST))
{
$choose_state = $_POST['choose_state'];
if (array_key_exists($choose_state, $states) && $choose_state > 0)
{
// Value does actually exist in array and is not item 0.
$chosen_state = $states[$chose_state]);
}
}
答案 1 :(得分:0)
以下示例假设您在var $state_key
中存储了为select提供的密钥...
试试这个:
$max = sizeof($states) - 1; // this is the number of possible values that you have, minus the default
if($state_key != 0 && $state_key > 0 && $state_key < $max)
{
// do whatever here, you've got good data at this point
}
顺便说一下,这也假设您的默认值始终是键#0(数组中的第一个)。
答案 2 :(得分:-1)
在php中验证表单提交:
在php中提交表单时,选择输入类型会在post中返回选定的值。所以你可以这样做:
$selectedindex = $_POST["choose_state"];
if($selectedindex == 0)
{
echo "Default item has been selected";
}
else{
echo "Other than default item has been selected ";
//you can do further validation here for selected item
//is in between 0 and 5 if you need to do so
}