我有一个联系表,并且通过使用“if”语句逐一检查每个字段来处理错误。我觉得很难,我似乎找不到更好/更有效的方式来使他们工作。如果一个(或多个)为真,我也希望标题显示“错误”。但是我无法让它们与单独的“if”语句一起使用。
这是我的代码:
$name = $_POST['name']; //get data from the form
$email = $_POST['email'];//get data from the form
$message = $_POST['message'];//get data from the form
if($name == ""){
echo"<p class='error'>Please enter a name.</p>";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
echo "<p class='error'>Your email address is not valid.</p>";
}
if($message == ""){
echo"<p class='error'>Please enter a message.</p>";
}
else{
echo"all ok, send email code...";
}
编辑:这些错误是用于窗体的验证。
最佳答案
But I cant get them to work with the separate "if" statements.
只是将错误存储在变量中
$error = array();
if($name == ""){
$error[] = "Please enter a name.";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
$error[] = "Your email address is not valid.";
}
if($message == ""){
$error[] = "Please enter a message.";
}
if (!$error) {
// do not echo anything here
// but send an email
// and use header("Location:") to redirect a user to thanks page
} else {
echo "Error";
foreach ($error as $line) {
echo "<p class='error'>$line</p>";
}
}
关于php - 更专业的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3816312/