0

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;
    }

}

}
?>
2
  • 1
    go read in the manual what return does Commented Apr 24, 2016 at 5:31
  • @Dagon Thank you, :) read up on it carefully, Know what it does got rid of those statements on all of them, then put all code into 1 issest($_POST["submit"]) and it worked :) Commented Apr 24, 2016 at 6:00

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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
  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.