-3
我正在做一個家庭作業任務,其中涉及使用PHP驗證表單。作業要求我通過switch語句來做到這一點,但我遇到了問題。我不知道我要去哪裏錯了,所以我要包括所有的PHP代碼:PHP中的表單驗證 - switch語句
<?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;
}
}
?>
的錯誤消息,然後用更多的PHP插入HTML這樣的:
<span class="error"><?php echo $fnameError;?></span>
的問題是,當我嘗試運行表單驗證,我得到這些一堆:
Notice: Undefined variable: fnameError
我想我的地方去錯在switch語句中,可能的情況下,語法,但我我一直在盯着你這足以讓我覺得自己無法想象。
以及之前存在,你得到的錯誤告訴你,你在驗證firstName時沒有錯誤(因爲你沒有設置它)。但總體來說你的問題是什麼? – Jeff
如果你有錯誤,你可能應該先檢查,如果你有任何錯誤,只嘗試顯示它們。我將它們推入一個數組'valErrors'並檢查該數組的長度。 – Jeff
以及爲什麼你檢查兩次,如果這些值是空的? – Jeff