Javascript Client-Side Form Validation Using Server-Side Form Validation

When developing a web form, it’s always nice to provide users with the instant feedback of invalid form fields that you get with Javascript client-side form validation. However, some users may not have Javascript enabled and therefore you must have server-side form validation no matter what. This often results in two sets of form validation code for the same form. To simplify your code and maximize code reuse, you can use jQuery Tools Form and power your client-side form validation use your server-side validation rules. Following is an example:

index.html – the javascript code which includes jQuery Tools’ Form Library

[cc lang=”javascript”]

$(document).ready(function(){
// server-side validation of a field
$(“[name=first]”).blur(function() {
var input = $(“[name=first]”).validator();
var value = $(“[name=first]”).attr(“value”);
$.getJSON(form.attr(“action”) + “?first=” + value, function(json) {
if (json !== ”) {
input.data(“validator”).invalidate(json);
}
});
});

$(“[name=last]”).blur(function() {
var input = $(“[name=last]”).validator();
var value = $(“[name=last]”).attr(“value”);
$.getJSON(form.attr(“action”) + “?last=” + value, function(json) {
if (json !== ”) {
input.data(“validator”).invalidate(json);
}
});
});

// server-side validation of entire form
var form = $(“#myform”);

$(“#myform”).submit(function(e) {
e.preventDefault();

var input = $(“#myform”).validator();
$.getJSON(form.attr(“action”) + “?” + form.serialize(), function(json) {
if (json !== ”) {
input.data(“validator”).invalidate(json);
}
else
$(‘#myform’).unbind(‘submit’).submit();
});
});
[/cc]

index.html – the html code for the form

[cc lang=”html”]

[/cc]

formprocessor.php – the PHP form processor

[cc lang=”php”]
$errors = array();

if (isset($_GET[‘first’]) && $_GET[‘first’] === ”) {
$errors[‘first’] = ‘First name required’;
}

if (isset($_GET[‘last’]) && $_GET[‘last’] === ”) {
$errors[‘last’] = ‘Last name required’;
}

if (count($errors) > 0) {
header(‘Cache-Control: no-cache, must-revalidate’);
header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’);
header(‘Content-Type: application/json; charset=utf-8’);
echo json_encode($errors);
}
[/cc]

The form processor does input validation and if fields are invalid, it builds an array of field names as keys and error messages as values and converts it to JSON format and returns the JSON to the AJAX call.

I don’t have time to explain how this works in detail but hopefully it’s self-explanatory.