PHP中的表单验证 - switch语句

时间:2016-03-06 01:01:15

标签: php validation

我正在做一项涉及用PHP验证表单的家庭作业。作业要求我通过switch语句执行此操作,但我正在处理问题。我不知道我哪里出错了所以我将包含所有PHP代码:

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);

$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$street = $_POST["street"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$email = $_POST["email"];
$payment = $_POST["payment"];

$storeNV = array("firstname" => "", "lastname" => "", "street" => "", "city" => "", "state" => "", "zip" => "",
    "email" => "", "payment" => "");

$inputNames = array_keys($storeNV);

foreach ($inputNames as $name) {
    $storeNV[$name] = "$_POST[$name]"; 
}

foreach ($storeNV as $name => $value) {
    if (isset($value) == false OR $value == "") {
        $blankError = "Something was left blank!";
        print "<h1>$blankError</h1>";
        break; #just one error message
    }
}

switch ($name) {
    case 'firstname' :
        if (empty($storeNV[firstname)) {
            $fnameError = "Required field";
        break;
        }
    case 'lastname' :
        if (empty($storeNV[lastname])) {
            $lnameError = "Required field";
        break;
        }
     case 'street' :
        if (empty($storeNV[street])) {
            $streetError = "Required field";
        break;
     }
     case 'city' :
        if (empty($storeNV[city])) {
            $cityError = "Required field";
        break;
     }
     case 'state' :
        if (!preg_match("/^[A-ZA-Z]*$/", trim($value))) {
            $stateError = "Standard state abbrieviations only";
        break;
        }
    case 'zip' :
        if (!preg_match("/^[0-9]{5}*$/", trim($value))) {
            $zipError = "Standard 5-digit zip codes only";
        break;
        }
     case 'email' :
        if (!filter_var($storeV[email], FILTER_VALIDATE_EMAIL)) {
            $emailError = "Invalid email";
        break;
        }
     case 'payment' :
        if (empty($storeNV[payment])) {
            $paymentError = "Please select one";
        break;
        }
}
?>

然后在HTML中插入更多PHP的错误消息,如下所示:

<span class="error"><?php echo $fnameError;?></span>

问题在于,当我尝试运行表单验证时,我得到了一堆:

Notice: Undefined variable: fnameError

我认为我在switch语句中的某个地方出错了,可能是在案例的语法中,但我一直盯着这个,我不认为我自己可以解决这个问题。 / p>

1 个答案:

答案 0 :(得分:2)

问题是变量$ fnameError未定义,如上所述。当fname通过验证时会发生这种情况。这有两种方法...

要么首先声明所有错误变量

$fnameError = "";
$emailError = "";

等。或者在回显之前检查变量是否存在

<span class="error"><?php if(isset($fnameError)) echo $fnameError;?></span>