Reputation: 1
Below is my PHP code, currently, it shows all errors and etc, but if one of them are correct it will submit the form, How could I change my code so that if 1 is not correct is does not submit
<?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;
}
}
}
?>
Upvotes: 0
Views: 69
Reputation: 8618
You could set a flag variable $submit to false by default.
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
}
}
Upvotes: 1
Reputation: 1876
Instead of else in the last use else if and pass this
else if(!empty($fName) && preg_match($pattern, $fName) && strlen($fName) < 20){
return true;
}
It just checks all your condition using AND operator and returns true only if all conditions are met
Upvotes: 2