Hybrid form validation: security of server-side (PHP) with efficiency of client-side (jQuery)

Person signing papers.
Simply sign here. And here. And here, here, and here.

I’ve built a lot of forms in my day, and to be honest, it’s not one of my favorite things to do. The designing and building aspect is fun, but the validation and error reporting, ehh.

We all know that server-side validation is a must, and technically speaking, client-side validation optional, but if you love your users, you’ll do it anyway.

The challenge then for you, as the web developer, is to vigorously ensure that the client-side (jQuery) and server-side (PHP) validation are identical, so you don’t have discrepancies that confuse your users.

The reason client-side validation makes users happy, is because the errors pop up right away and the page doesn’t need to be reloaded.

What if you could trade the pain of writing a client-side validation script with making  server-side validation instantaneous?

Yes, AJAX comes to mind, however, the one thing people tend to do with that is display all the errors grouped together, because the AJAX response either updates or adds a div below or above the form, making the user have to figure out which error belongs to which field.

Project

The goal is to validate forms in the most efficient and user-friendly way, without having to compromise speed or security.

Requirements

  • Completely omit client-side validation
  • Display errors instantaneously next to corresponding fields
  • Prevent the page from being refreshed

Solution

The user fills out a form and it gets submitted via jQuery. If the submission takes just a bit longer, a processing message will appear.

A separate processing script will validate each field and upon error, store that error in an array using the field’s label as the array item’s key and the error as the array item’s value.

At the end of the validation, it will send the form back by calling the form’s function — a user-defined PHP function — with the error array as an argument.

jQuery then replaces the existing form on the page with a new form that displays the errors underneath each field. jQuery’s on event handler then ensures that the replaced form is re-submittable.

Implementation

Below is the user-defined PHP function that creates the HTML form:

// Returns a login form
// @param (array) errors [optional]
// @return (string) login form
function getLoginForm($errors = false) {
  $output .= '<form action="#" name="login" method="post">';
    $output .= '<h2>Sign in to ' . APPNAME . '</h2>';
    $output .= '<div class="field">';
      $output .= '<label for="username">Username</label>';
      $output .= '<input type="text" id="username" name="username" autofocus="autofocus"' . getPostValue('username')  . ' />';
      if(isset($errors['username'])) {
        $output .= '<div class="help">' . $errors['username'] . '</div>';
      }
    $output .= '</div>';
    $output .= '<div class="field">';
      $output .= '<label for="password">Password</label>';
      $output .= '<input type="password" id="password" name="password"' . getPostValue('password')  . ' />';
      if(isset($errors['password'])) {
        $output .= '<div class="help">' . $errors['username'] . '</div>';
      }
    $output .= '</div>';
    $output .= '<div class="message"></div>';
    $output .= '<div class="button">';
      $output .= '<button type="button" name="commit" disabled="disabled">Login</button>';
    $output .= '</div>';
  $output .= '</form>';
  return $output;
}
  • On line 4 you see the optional argument. The variable is set to false so that PHP doesn’t complain when the function is called without a parameter.
  • On line 6 I’m using a named constant to display what the user is logging into. You could replace that with static text.
  • On line 9 I have another custom function called getPostValue() that basically escapes the user’s input before displaying it inside the field.
  • On line 10 we’re checking to see whether an array item with a key, that matches the field’s label, exists. If it does, we know to display an error, if not, that whole help div container is omitted.

Here is how the rendered form looks like in HTML:

<div class="init">
  <form action="#" name="login" method="post">
    <h2>Sign in to SME</h2>
    <div class="field">
      <label for="username">Username</label>
      <input type="text" id="username" name="username" autofocus="autofocus" />
    </div>
    <div class="field">
      <label for="password">Password</label>
      <input type="password" id="password" name="password" />
    </div>
    <div class="message"></div>
    <div class="button">
      <button type="button" name="commit" disabled="disabled">Login</button>
    </div>
  </form>
</div>
  • On line 1 we need to wrap the form in a div, so we can later monitor it with jQuery. What happens is that jQuery will replace the entire form with one that shows the errors. Because that new form is a new object to the page, jQuery doesn’t know about it. It needs a fixed element on the page, such as the init div, whose contents it can monitor.
  • On line 2 you’ll notice that the action attribute is empty. This particular project requires users to have JavaScript turned on, but if you expect users without JavaScript, it’s a good idea to enter the path of the processor,.
  • On line 12 we will show a message to the user when the button gets clicked, so they know the form is processing.
  • On line 14 you’ll notice that I used the button tag to render a button as apposed to the classic <input type=”submit”>. I do that simply so I can style my text fields without having to worry that it will affect my buttons. My button is by default disabled and I then enable it with JavaScript, that way if JavaScript is turned off, the form can’t be submitted. Lastly, my button is of type=”button”, which by default doesn’t do anything (I assign an event handler with jQuery later). You’d make it of type=”submit” if you wanted that button to work without JavaScript.

Below is the jQuery that is in charge of submitting the form:

$(document).ready(function(){

  initBinding();

  // Send any form to its specific processor
  $('body').on('submit', 'form', function(e){
    var form = $(this);
    form.find('button[name=commit]').attr('disabled', 'disabled');
    form.find('.message').delay(100).queue(function() {
      $(this).html('<div class="pending">Sending your request... please wait...</div>');
    });
    $.post('process.php?p=' + form.attr('name'), form.serialize(), function(response) {
      form.parent('div').html(response);
      initBinding();
    });
    e.preventDefault();
  });

  function initBinding() {
    // Enable the form's submit button and assign event handler
    $('button[name=commit]').removeAttr('disabled').click(function() {
      $(this).trigger('submit');
    });
  }

});
  • On line 3 I’m calling a function that enables my disabled submit button and assigns a click event to it, so it can submit the form, since my button doesn’t natively do that.
  • On line 6 we’re using jQuery’s on event handler, which basically monitors the HTML body and looks for changes in a form element. This is important so that the form can be resubmitted. When the form gets replaced, it’s an unknown object on the page, however, since jQuery is monitoring it, it will convert the newly replaced form to a submittable form.
  • On line 8 I’m disabling the button, so while the form is processing, it can’t be submitted a second time.
  • On line 9 you’ll notice that we delay the “processing” message slightly, because if it submits right away, there’s no reason to flash it on the screen, but if it takes a bit longer, the user should know that something is happening.
  • On line 12 is where we actually post the form. I’m sending it to process.php, which contains a switch control structure that receives the form attribute’s name, so that the processor knows which fields to expect and validate.
  • On line 14 I’m calling initBinding() again, so that the newly replaced form’s submit button will be re-enabled and can submit again.

Conclusion

You get an easily maintainable and secure form for which you don’t have to write any client-side validation. The form is submitted via jQuery, which doesn’t require the page to be reloaded, and the validation appears almost instantaneous to the user, just as if you had used client-side validation.

If you have any questions or suggestions, please feel free to leave comments below.

Featured image by Scott Graham.


Comments (4)

Previously posted in WordPress and transferred to Ghost.

Jami
June 6, 2012 at 2:24 pm

How is this at stopping hackers, and those wishing to exploit website forms?

Ryan Sechrest
June 6, 2012 at 2:43 pm

This post doesn’t go through the actual form validation, because it is intended to showcase how one can setup a form that can be validated by the server, but at the same time, keep the setup user-friendly and maintainable.

When it comes to validation, there are many considerations, so it wouldn’t be feasible to cover all those, however, I have a more detailed post on validation here that goes through some of its use cases.

jayem
January 20, 2013 at 3:58 am

just notice, it only considers if there is an error…
what about when the post is successful, what happens then?
i mean, how should the code handle that?

Ryan Sechrest
January 20, 2013 at 2:30 pm

In that case, instead of sending the form HTML back in the response, you could send back something like true. Then you wrap line 13 and 14 in an if statement that checks if response is true. If it is, redirect the user to another page, if it isn’t, display the form with error messages.