Question

Given the following code example, what would I need to add to the check_input function so that it deals with missing / required form fields. Basically, all I am trying to do is to show the end user an error message on the top of my form that says something like "Fields marked with a * are required" if they try to submit the form without filling out all the required fields.

Any help would be greatly appreciated and thank in advance for your time.

 // Don't post the form until the submit button is pressed.
if(isset($_POST['submit'])) {

  echo( 
   check_input($_POST['name']) . <br> .
   check_input($_POST['city']);

}

// check_input function
function check_input($data)
{
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data, ENT_QUOTES);
  return $data;
}

The Form

<form action="test.php" method="post">
  <input type="text" name="name">
  <input type="text" name="city">
  <input type="submit" name="submit" value="submit">
</form>
Was it helpful?

Solution

<?php
// Don't post the form until the submit button is pressed.
$requiredFields = array('name', 'city');    // Add the 'name' for all required fields to this array
$errors = false;
if(isset($_POST['submit'])) 
{
    // Clean all inputs
    array_walk($_POST, 'check_input');

    // Loop over requiredFields and output error if any are empty
    foreach($requiredFields as $r) {
        if( strlen($_POST[$r]) == 0 ) {
            $errors = true;
            break;
        }
    }

    // Error/success check
    if( $errors == true ) {
        echo 'Fields marked with a * are required';
    }else{
        // no errors
        // ...
    }
}

// check_input function
function check_input(&$data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES);
    return $data;
}
?>

PS: I noticed a quote mismatch in your form HTML. The method should read method="post", not method="post'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top