POST Validation Loop


You have an HTML form with a variety of inputs. The action attribute of the form points to a PHP file that contains the code below.

Notes about code

This code starts by creating an array that holds the name of various inputs being submitted via a POST. getFormData() is then called, where the required fields are passed in. Inside the function an array is created to hold various pieces of data related to the form. $formData['valid'] is a boolean referencing if all data was provided and valid, $formData['fields'] is an array keyed by the name of the input with their respective value from the POST data, $formData['notValidFields'] is an array that will contain the names of any inputs that were not passed or that had non-valid data.

This logic can be easily extended with regular expressions to check for stricter data, such as email addresses and urls.


$requiredFields = array('field1', 'field2', 'field3', 'field4');
$formData = getFormData($requiredFields);

function getFormData($requiredFields){
       $formData = array();
       $formData['valid'] = true;
       $formData['fields'] = array();
       $formData['notValidFields'] = array();

       for($a = 0; $a < count($requiredFields); $a++){
               $field = $requiredFields[$a];
                       $value = $_POST[$field];
                               $formData['valid'] = false;
                               $formData['notValidFields'][] = $field;
                               $formData['fields'][$field] = $value;
                       $formData['valid'] = false;
                       $formData['notValidFields'][] = $field;
       return $formData;


  1. OldGuy
    Permalink to comment#

    Excellent snippet. input validation is one of those things that most people don’t seem to know about or don’t bother with. Thanks for posting this!

    Anytime user input is involved though, it’s a good idea to sanitize the input before anything else. Just add this line (right after the opening php tag on the top line):
    $_POST = sanitize($_POST);
    and define the functions somewhere. I use sanitize routines similar to these.

  2. charly
    Permalink to comment#

    nice. and I suggest you to put an example in order to see where the code snippet must be included. if in the the form or in the action. bye.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.