While each of the tutorials on the various aspects of creating completely unobtrusive validation of your forms using JavaScript have shown the particular pieces of code that relate to the particular part of the validation being discussed, you'd need to put that together with many of the fragments in the earlier articles in order to build a working script. Each of the articles assumes that your form and script already include those things already presented in the earlier tutorials.
To save you the trouble of actually trying to figure out how to assemble all of those pieces into a working script, I have included below a complete copy of all the HTML and JavaScript presented in this series so that you can see for yourself all at once how it all fits together.
As you can see from the following HTML, there are no references to the script in the HTML whatsoever apart from the script tag right at the end.
We do have a couple of HTML 5 attributes attached to the input fields since a couple of the tutorials demonstrated how we can use JavaScript to apply the validations that those attributes are meant to apply even in older browsers that don't actually understand HTML 5 such as being able to define a form field as required. Also note that while the email field can be defined as type="email" in HTML 5, I haven't done so in this example HTML since the purpose of including that field in the example form is to demonstrate how to apply validation based on the pattern attribute.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Unobtrusive Form Field Validation</title>
</head>
<body>
<form action="#" method="get">
<fieldset>
<legend>Message</legend>
<div id="message"> </div>
</fieldset>
<fieldset>
<legend>Form to test validations</legend>
<div><label for="nam">Name</label> <input type="text" id="nam" required="required"></div>
<div><label for="email">Email</label> <input type="text" id="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$"></div>
<div><input type="submit" value="submit"></div>
</fieldset>
</form>
<script type="text/javascript" src="validate.js"></script>
</body>
</html>
Of course the above HTML also requires the JavaScript in order to be able to actually perform the validations on the fields within the form. In order to reduce the chances of the validation interfering with any other scripts that we might have in our page, we are using event listeners to detect when the form fields lose the focus (or attachevent in older versions of IE that don't support event listeners).
Our code also retrieves which field triggered the event, has code to stop the event from propogating beyond the form field, and extends the String object to allow us to trim whitespace from whatever was input.
JavaScript
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
var eProp = type + fn;
ob['e'+eProp] = fn;
ob[eProp] = function(){ob['e'+eProp]( window.event );};
ob.attachEvent( 'on'+type, ob[eProp]);
};
whichElement = function(e) {
var targ;
targ = (window.event) ? window.event.srcElement : e.target;
if (3===targ.nodeType) {
targ = targ.parentNode;
}
return targ;
};
stopDef = function(e) {
if (e && e.preventDefault)
e.preventDefault();
else if (window.event && window.event.returnValue)
window.eventReturnValue = false;
};
String.prototype.trim = function() {
var re = /^\s*(.*?)\s*$/;
return this.replace(re,"$1");
}
errorMessage = function(mes) {
document.getElementById('message').innerHTML = mes;
}
validateRequired = function(e,elem) {
if (elem === undefined) elem = whichElement(e);
elem.value = elem.value.trim();
if (elem.required && '' === elem.value) {
errorMessage('Please enter values in all required fields.');
stopDef();
return false;
}
errorMessage(' ');
}
validatePattern = function(e,elem) {
if (elem === undefined) elem = whichElement(e);
if (!elem.pattern) return true;
var re = new RegExp(elem.pattern);
if (!elem.value.match(re)) {
errorMessage('Entered value does not match pattern for '+elem.id+' field.');
stopDef();
return false;
}
errorMessage(' ');
}
addEvent(document.getElementById('nam'),
'blur',
validateRequired);
addEvent(document.getElementById('email'),
'blur',
validatePattern);
A couple of things to note about the above JavaScript. Firstly, I haven't included the code that you'd need in order to revalidate the entire form when the submit event is triggered. That function would just call the other validation functions over again but passing in a second parameter identifying which field the validation is to be applied to since the validation is no longer of the field that triggered the event. Finally, while the two validations actually shown in this example rely on HTML 5 attributes to supply information about what validation is needed (and therefore allow the validation function to be more easily shared across multiple form fields) there is nothing to prevent your using a more conventional approach to the actual validation code and hard code all of the validation processing directly into the JavaScript rather than using HTML attributes to supply part of it.
Try out the working script.
