下面是我的PHP代码,目前,它显示所有错误等,但如果其中一个是正确的,它将提交表单,我如何更改我的代码,以便如果1不正确则不提交
<?php
$cusMsg = "";
$fNameMsg = "";
if (isset($_POST["submit"])) {
$id = $_POST["custid"];
if(empty($id)) {
$cusMsg = '<span class="error"> Field was left empty</span>';
} else if(!is_numeric($id)) {
$cusMsg = '<span class="error"> Customer ID must be numeric</span>';
} else if(strlen($id) != 6) {
$cusMsg = '<span class="error"> Customer ID must be 6 digits long</span>';
} else {
return true;
}
}
if (isset($_POST["submit"])) {
$fName = $_POST["customerfname"];
$pattern = "/^[a-zA-Z-]+$/";
if(empty($fName)) {
$fNameMsg = '<span class="error"> Field was left empty</span>';
} else if(!preg_match($pattern, $fName)) {
$fNameMsg = '<span class="error"> First name must only containt letters and hyphens</span>';
} else if(strlen($fName) > 20) {
$fNameMsg = '<span class="error"> First name must not be longer than 20 characters</span>';
} else {
return true;
}
}
}
?>
答案 0 :(得分:2)
而不是在最后一次使用,否则传递此
else if(!empty($fName) && preg_match($pattern, $fName) && strlen($fName) < 20){
return true;
}
它只是使用AND运算符检查所有条件,并且仅在满足所有条件时才返回true
答案 1 :(得分:1)
默认情况下,您可以将标志变量$ submit设置为false。
if (isset($_POST["submit"])) {
$submit = false; // Add this
$id = $_POST["custid"];
if (empty($id)) {
$cusMsg = '<span class="error"> Field was left empty</span>';
} else if (!is_numeric($id)) {
$cusMsg = '<span class="error"> Customer ID must be numeric</span>';
} else if(strlen($id) != 6) {
$cusMsg = '<span class="error"> Customer ID must be 6 digits long</span>';
} else {
$submit = true;
}
// Now check the value of $submit and write your code accordingly.
if ($submit) {
// Write your submit action
} else {
// Other action
}
}