JavaScript: It’s Just Not Validation!

Tweet

The term "JavaScript validation" is a somewhat misleading one for describing the process of assisting the users to fill forms out correctly. In fact, the back-end code performs the validation — JavaScript merely provides assistance. But when the validation and assistance don’t come from the same source, they do nothing but confuse people.

Web forms are the means by which HTML became interactive — it’s through forms that web applications receive information from end users. Sometimes, this information flow can be laid-back, relaxed, and unrestricted. At other times, the information flow must be vetted to ensure the web form data is in the right format, particularly information like email addresses, shipping addresses, and credit card numbers. We all know that the key to good data is back-end validation, and that front-end validation using JavaScript helps the user to get it right without having to wait for a round-trip to the server. Developers have already combined JavaScript functionality with their back-end validation. However, most treat these forms of validation as if they were the same task, using different technology.

Strictly speaking JavaScript validation isn’t validation — it’s input assistance. Anyone can bypass JavaScript; it’s an aid, not a gate. It simply helps to give your users the confidence to hit that big submit button.

JavaScript input assistance, when built separately from back-end validation, is not ideal. At worst, the two piece of functionality work differently, and what’s valid on the client side isn’t valid at the server. At best they work fine — initially. But with validation logic in multiple locations, there’s an increasing likelihood that only one will get updated when changes are required, at which point we get inconsistent results.

Finally, back-end validation is required. JavaScript assistance is nice.

Code Time

With all of this in mind, I created the Y-Validator, using PHP5 for the back end. There’s a test version available to play with, and you can download the code to follow along if you like.

In PHP, we specify validation by instantiating the yValidate object:

<?php 
 require('y-validate.php');
 $v = new yValidate();
 $v->add('name','+NAME','namefeedback','Required, valid names are letters, numbers and '-()?'');?>

The y-validate.php library contains the yValidate class. We start by feeding the object the various inputs that need validation via the add() function:

  • The first parameter is the ID or Name of the field; radio buttons and checkboxes use Name (and [] is used for checkboxes so that PHP receives an array of values), while all other fields use ID.
  • The second parameter is the validation type, defined in the private object variable regValidations, which maps the parameter string with a regular expression for validation. It’s prefixed with + for required fields.
  • The third parameter specifies the ID of the tag in which the feedback is placed.
  • The fourth parameter is the message text that tells the user what’s expected.

From this point, validating the submitted code is a matter of passing the $_POST variable through $v->validateAll($_POST). It uses the mappings defined in $v->add(...) to validate the input, returning true or false on validation, plus an array of errors, if applicable. That’s the back end all sewn up!

<script type="text/javascript" src="y-validate/js/y-validate.js"></script> 
<script type="text/javascript">
 <?php echo $v->buildJS(); ?>
 <?php $v->jsValidations(); ?>
</script>

When we’re building the front end to capture input, we include the front-end script y-validate.js. This creates a class that’s similar to the PHP script above. To link the two validations, we call two methods of the PHP object. First, $v->buildJS instantiates the JavaScript validation class as an object, and attaches validation type checks to the fields, and the submit button, that were attached to the PHP object with $v->add(...). Secondly, jsValidations prepares window.onload to attach the same Name + Regular Expression relationships held in the PHP object to the fields in the form.

Importantly, the jsValidations method ensures the validation for the back end becomes the assistance checks on the front end. Update the back end and the front end is also updated, which means the validation can’t get out of step.

<label for="name">Your name <?php echo $v->fieldFeedback('name','namefeedback',$namefeedback);?></label> 
<input type="text" name="name" id="name" value="<?php if (isset($name)) echo $name;?>" />

Both the back- and front-end code needs to be able to inform the user should an input issue arise. Naturally, the fields themselves have labels, and that’s the perfect place to put the feedback for users when an input needs correction. fieldFeedback takes three parameters:

  1. The first is the field to which the feedback is appropriate.
  2. The second is the ID of an <em> to create in order to catch feedback; this maps to the third parameter of $v->add(...).
  3. The third parameter is the initial prompt defined in the fourth parameter of $v->add(...).

So, aside from the second parameter in $v->add(...) that sets the validation to use, the parameters between the two map together nicely.

Using a single location for feedback means the user has one place to look for help, whether JavaScript is enabled or not. Since the validation and input assistance capabilities are built from the same object, the feedback text is identical for both the validation and the input assistance. Also, to highlight the assistance nature of the front-end validation, the feedback message is put into the feedback field before any interaction occurs. This prompts the user for the expected format beforehand, letting them get it right the first time.

Once the page has loaded, the window.onload event fires and links the JavaScript input assistance to all the fields and the submit button; this was set up in $v->jsValidations. When the user makes a change to a field, JavaScript events attached by window.onload fire, checking the values using the configured regular expressions.

Already Out There

I’ve used PHP for my library (see below), but other languages and frameworks have hit upon this idea, too:

  • PHPCake has an extension called JS Validator; it relies on AJAX for back-end validation.
  • Ruby on Rails uses AJAX to farm the validation directly to the back-end validation.
  • Work is currently being done on CodeIgniter.
  • Python’s got a clever guy who released a library about the same time I started work on this one.

Aside from the Python solution, most validators for this concept rely on AJAX to send the fields back to the server for validation. Since the validation requirements don’t generally change within the few seconds of a page request and a user inputting data, that’s an extra overhead for per-field validation. Also, these scripts don’t hook into the best method of helping the user — telling them what’s expected first. By attaching the English description of the validation to each field, and having that appear as a helpful hint first to prompt the user on what to enter, we help the user to get it right first time. How many times have you looked at a form and growled "Why didn’t you tell me that when I started?"

Conclusion

The use of a central object to manage both the validation and input assistance tasks creates a consistent end user experience even with JavaScript disabled.

  • We have one place to update both the enhancement (JavaScript assistance) and the required functionality (back-end validation). Therefore, the two can’t get out of step, and we can ensure a seamless experience for the user.
  • We have one place to find the enhancement, so it’s less confusing for future maintainers of our code to located the points at which various validations and assistances are implemented in the code.
  • The code also promotes the separation of behaviour from presentation. The programmer programs the validation and the designer implements the presentation of the feedback.
  • The user feels in more control, having confidence in hitting the big submit button.

Don’t forget: the code for the PHP-Validate and a sample form is available for download.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments