Skip to content
Advertisement

PHP: how to correct if else statement to check if POST array is empty or not, and if not check REGEX to continue

I’m working on an e-commerce website project, and I’m trying to validate customer’s information using PHP. And I’m here trying to check if the customer put his/her phone number, and to check if the phone number is in the correct form. So first, I check the POST array if it’s empty or not, if it is empty, I show an error message “Phone number must be entered”. And if there is a phone number, I check the REGEX and if it does not match, I show an error message “Phone number is invalid”. And everything is correct, just proceeds. But somehow, below my code, does not check REGEX. If it is empty, it shows an error message for the empty field, but not REGEX. Why is this so?

if (!empty($_POST)) {
  $error = false;
  if (empty($_POST["phone"])) {
      echo "<p class='errorMessage'> Phone must be entered. </p>";
      $error = true;
  }
  if (!empty($_POST["phone"])) {
      if (!preg_match("/^[2-9]d{2}-d{3}-d{4}$/", $_POST['phone'])) {
          echo "<p class='errMessage'>Phone number is invalid</p>";
      }
  }
  if (!$error) {
      header("Location: confirmation.php");
      exit;
  }
}

And here is the HTML part:

<tr>
  <th><label for="phone">Phone Number</label></th>
  <td><input class="inputField" type="text" id="phone" name="phone"
  <?php
  if (isset($_POST["phone"])) echo "value='" . $_POST["phone"] . "'";
  ?>></td>
</tr>

Advertisement

Answer

This is because you don’t declare error if the regex is invalid, so the code proceeds :

if (!empty($_POST)) {
  $error = false;
  if (empty($_POST["phone"])) {
      echo "<p class='errorMessage'> Phone must be entered. </p>";
      $error = true;
  }
  if (!empty($_POST["phone"])) {
      if (!preg_match("/^[2-9]d{2}-d{3}-d{4}$/", $_POST['phone'])) {
          $error = true;
          echo "<p class='errMessage'>Phone number is invalid</p>";
      }
  }
  if (!$error) {
      header("Location: confirmation.php");
      exit;
  }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement