需要php表单来命名哪些必填字段尚未填写

时间:2010-03-02 21:33:56

标签: php forms

我的php表单包含必填字段,但该消息不会让用户知道哪个字段尚未输入。我怎么能这样做?

//if statement to check required fields
if ($name && $phone && $email && && $address && $city && $state && $zip && $month && $date && $year && $contact)...
    //if some required fields were not filled out
    echo "Please make sure you fill in all required fields<br>Click <a href=\"javascript:history.back(1)\">here</a> to return to our form.";
}

3 个答案:

答案 0 :(得分:7)

这是一个简单的例子......

// An array of required fields, these fields must not be empty
$requiredFields = array('name', 'email');  

// Iterate through required fields
foreach ($requiredFields as $fieldName)
{
    // Does this field have a value?
    if (empty($_REQUEST[$fieldName]))
    {
        echo 'rawr! go back and fill out ' . $fieldName . "<br>\n";
    }
}    

答案 1 :(得分:0)

看起来每个都是布尔值;我假设你在单独检查每个值时提前设置它们。我不会在最后使用单个echo,而是在开头初始化$message变量,并将所有错误消息放在那里。最后,只需echo $message'

答案 2 :(得分:0)

只是单调乏味的if / else子句。您可以使用验证框架来解决这个问题。

if (empty($name))
   echo "Name is not filled out";
if(empty($phone))
   echo "Phone is not filled out";

如果你想得到幻想,那就行了

foreach (array("name","phone") as $var)
{
   if (empty($$name))
      echo "$var is not filled out";
}