PHP

Checking Mandatory Fields

if (isset($_POST['Submit']) &&
    isset($_POST['textfieldname']) &&
    trim($_POST['textfieldname']) != '')

When validating a form, most of the time the emphasis is on mandatory fields. You can check if they contain values in two ways:

  • Check whether the fields exist in $_GET/$_POST

    if (!isset($_GET['fieldname')) {
      // Error!
    }
    

  • Check whether the values in $_GET/$_POST contain information other than whitespace

    if (trim($_GET['fieldname') == '') {
      // Error!
    }
    

It is very important that you combine both techniques. You always have to check for a field's existence using isset() to avoid error messages when trying to access array values that do not exist. But you always have to check whether there is something within the field apart from whitespace because text fields are always submitted. In addition, when empty, isset() always returns true independent of the field's value.

Validating Mandatory Fields (mandatory.php; excerpt)
<?php
  if (isset($_POST['Submit']) &&
      isset($_POST['textfieldname']) &&
      trim($_POST['textfieldname']) != '') {
    echo '<h1>Thank you for filling out this
      form!</h1>';
  } else {
?>
  <form method="post" action="
<?php echo htmlspecialchars($_SERVER['PHP_SELF']);
   ?>">
    <input type="text" name="textfieldname"
      value="<?php
  echo (isset($_POST['textfieldname'])) ?
    htmlspecialchars($_POST['textfieldname']) : '';
      ?>" />
    <input type="submit" name="Submit" />
  </form>
<?php
  }
?>

The code for prefilling the form element has been left intact so that this code snippet can be merged with other code snippets. So, if the form has only partially been filled out, the correct form fields are prefilled.

by BrainBellupdated
Advertisement: