Bulletproof Your Online Forms for Mobile Devices with PHP – Part 2

In the last post, we explored how to set up an online form using HTML and PHP. In this post, we’re going to finish setting up the logic to store form field values and validate the form.  If you haven’t read the last post and want to catch up, please click here to go to part 1.

Step 1: Add PHP Functions for Setting/Resetting Variables

In the last post, we set the form up so the value for each form field is set to a corresponding PHP variable. Now we need to make sure that when the form field changes and a user action (like submitting the form) takes place, the PHP variables get set to the newly updated form field values.  This is a simple process, as we just have to create a function to set the PHP variables.  And while we’re at it, we can create another function to reset the PHP variables for our ‘Clear Form’ button.  Here are the functions we’ll use.  Note that we need to use the ‘global’ keyword inside the functions to access and successfully update the variables.

function setVariables() {
  global $user_name;
  $user_name = $_POST["user_name"];
  global $user_email;
  $user_email = $_POST["user_email"];
  global $user_message;
  $user_message = $_POST["user_message"];
}
function resetVariables() {
  global $user_name;
  $user_name = “”;
  global $user_email;
  $user_email = “”;
  global $user_message;
  $user_message = “”;
}

Again, these functions will eventually get called when a user clicks on the Submit or Reset button, respectively.

Step 2: Add PHP Functions for Form Field Validation

Now it’s time to write out the validation functions for the form.  In our example, we have three fields.  The name and message fields will be a simple character count for their validation.  In the email validation, we will use one of the well known regular expressions that will check the email value for correct syntax.

For the simple text input, we’ll create a function that accepts two arguments.  The first argument will be the value to get validated, and the second will be the minimum number of characters that need to be present in the first value.  Inside the function, there will be some simple conditional logic that will check the string length of the first value to the minimum number of characters.  We’ll also set a return value of ‘y’ or ‘n’ so we’ll know whether or not our value is valid.  Here’s what our simple text input validation function will look like:

function validateTextInput($str, $minLength=1) {
  if (strlen($str) < $minLength) {     $lValid = ‘n’;   } else {     $lValid = ‘y’;   }   return $lValid; }

For the email validation function, we'll simply pass in the value to check as the one and only argument.  Inside the function, the conditional logic checks the value against the aforementioned regular expression.  And, like the text input validation function above, this one also returns a 'y' or 'n' value telling us whether or not the value is valid.  Here's what our email validation function will look like:

function validateEmail($str) {
  if (!eregi(“^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”, $str)) {
    $lValid = ‘n’;
  } else {
    $lValid = ‘y’;
  }
  return $lValid;
}

Step 3: Add PHP Function for Overall Form Validation

Now that we have set up the individual form field validation functions, we'll need a master function that will be called when the user clicks the Submit button.  It will validate all of our fields, and will hold logic to either show an error or send the form.  Here's what the function will look like.  An explanation of the function is below the function.

function validateForm() {
  $default_error = “There was a problem with your entry. Please correct the following fields.”;
  $error = "";
  // Set up global variables to check
  global $user_name;
  global $user_email;
  global $user_message;
  // Perform validation for fields
  $valid_user_name = validateTextInput($user_name, 1);
  $valid_user_email = validateEmail($user_email);
  $valid_user_message = validateTextInput($user_message, 5);
  if ($valid_user_name != ‘y’) {
    $error .= “<li>Your Name</li>”;
  }
  if ($valid_user_email != ‘y’) {
    $error .= “<li>Your Email</li>”;
  }
  if ($valid_user_message != ‘y’) {
    $error .= “<li>Message</li>”;
  }
  // Return error value or send form
  if ($error) {
    echo “<div class=\”error\”>”;
    echo “<label>” . $default_error . “</label>”;
    echo “<ul>”;
    echo $error;
    echo “</ul>”;
    echo “</div>”;
  } else {
    sendForm();
  }
}

First, the function will have two variables: $default_error and $error.  As you noticed, the $default_error has the general text calling out that there's an error, and the $error variable is blank by default.

Next, we set up the global variables that we need to check.

Third, we set up a unique variable that will be set to the return value of our individual field validation functions.  After these variables are set up, we put in conditional logic that appends the $error variable with <li> tags if the variable isn't set to 'y'.

Finally, there is conditional logic that checks the $error variable.  If this variable is set to anything other than its default blank value, we echo out some HTML markup that writes out our $default_error message, and then lists out each individual form field that is invalid.  If the variable is still blank, we call the sendForm() function (not included in this article - you can write that out depending on the needs of your project).

Step 4: Add Markup and Logic for Submit and Reset Button Actions

Now that we have everything set up, we obviously need to be able to call our validation and reset functions, based on what button the user clicks.  I am a fan of putting this logic inside of a <div> tag at the top of the form.  Since the validation function echos out a message if invalid, it will thus echo out to a div tag that we can style however we want.  Same with the reset logic, as we will first display a "are you sure you want to reset?" message with a 'Yes' and 'No' button.  Here's the markup we'll insert for this logic, that we'll place between the opening <form> tag and the first <label>.

<!– Error Message –>
<div id=“error-message”>
  <?php
  if ($_POST["submit"]) {
    setVariables();
    validateForm();
  }
  ?>
</div>

<!– Reset Confirmation Message –>
<div id=“confirm-reset”>
  <?php
  if (isset($_POST['reset'])) {
    setVariables();
    echo “<div class=\”confirm\”>”;
    echo “<label>Are you sure you want to reset?</label>”;
    echo “<div class=\”hidden\”><br /></div>”;
    echo “<input type=\”submit\” class=\”button\” name=\”reset-yes\” value=\”Yes\” />”;
    echo “<div style=\”display:inline; width:16px;\”>  </div>”;
    echo “<input type=\”submit\” class=\”button\” name=\”reset-no\” value=\”No\” />”;
    echo “</div>”;
  } else if (isset($_POST['reset-no'])) {
    setVariables();
  } else if (isset($_POST['reset-yes'])) {
    resetVariables();
  }
  ?>
</div>

As you see, the error message <div> tag has conditional logic that checks for $_POST["submit"].  If our submit button is clicked, the two functions inside this conditional statement are fired off.  First, we call the setVariables() function, which as outlined above, sets all of our global PHP variables to the value of the form fields.  After we have called this function, we call our validateForm() function that validates each field and checks whether to display an error message or send the form.

The reset <div> tag is a bit more detailed.  Our form 'Reset' button is set up with name 'reset', which is equivalent to $_POST['reset'].  This is the first check of our conditional logic here, which calls the setVariables(), and echos out a <div> tag with the reset confirmation message and accompanying 'Yes' and 'No' buttons.

The second and third checks of the reset conditional logic check for the 'Yes' and 'No' button clicks.  If the 'No' button is clicked, we simply call the setVariables() function.  If the 'Yes' button is clicked, we call the resetVariables() function which as outlined above, resets all variables and therefore erases the form field values.

Wrapping It Up

As I mentioned at the beginning of the article, this is useful because all of the logic is done with PHP, and can thus be used on any browser and device, regardless of how the settings are configured.  What I like to do is to put all of the logic in its own file, and then include it in the page wherever I need it.  That way, if I have a completely separate set of files for full web vs. mobile, for instance, I can still use the same one file that contains the form, and style it with CSS depending on what version of the site the user is seeing.

Also, at this point, feel free to add in your own CSS and/or other HTML markup for how the form is set up and will be displayed.

Also, since there's A LOT of code and logic here, I have gone ahead and packaged up the files in a zip file that you can download for your convenience.  The zip file includes some sample CSS styles that I have set up to customize the look of the form.

Until next time, happy coding!

3 Responses to this post:

  • Anthony,
    This is awesome! I have been working to learn more using CSS3 and working a bit more in PHP. This is an extremely helpful tutorial and I am learning a lot from you. You’ve definitely gone far beyond my expectations in such a short amount of time. You are a great developer! Keep on doing the great work and sharing your knowledge. You are a true blessing in this industry.

  • Kevin says:

    Anthony,

    Thx for the tut…can you tell me how to submit the form data to the db after the form is validated? I have a processor.php page set up to accept the data but I don’t know how to submit the data to it.

    thanks,
    Kevin

  • Anthony says:

    Kevin,

    Here’s the URL to some sample PHP code (zipped up for online transfer) for opening connection, querying, writing to, and closing connection to a database. All values for database variables are made up, as it’s a sample. But there are comments throughout the file letting you know what each part does. Hope it helps!

    http://www.hesslerdesign.com/blog/wp-content/uploads/2011/01/sampleDBTableValuesWrite.zip

    AH

Leave a Comment