Today I thought I would share with you what I consider to be a fantastic way to handle form validation in javascript. Of course you need to remember that you have to validate any user input on the server side, but it’s nice to do things on the client side also, so they don’t have to wait as long for a response.
My approach to form validation in javascript involves 2 parts. First off is a extensible object that includes a variety of validation functions that I can have at my disposal. Secondly, I always format my forms with particular IDs, so that I can easily add error messages in javascript. First off, lets discuss the form layout (the easy part). The general rule of thumb here is to create a spot below the form element that will hold the error message, and give it an ID that is the same as the element, with ‘_error’ after it. So
Email:
Here the class ‘msg’ simply defines it as being hidden. Then with javascript if we determine email to be invalid, we can set the spans innerHTML to the text we want, and the class to something that will make it appear.
The second part is the fun javascript. What I do is create an empty object which i then prototype out with validation functions. Here is the code:
function Validator()
{
}
/**
* Check Email Function
*/
Validator.prototype.checkEmail=function(ELEM, EVENT)
{
if(EVENT)
{
var scope = this;
YAHOO.util.Event.addListener(ELEM, EVENT, function(){scope.checkEmail(ELEM);});
return false;
}
try
{
var elem = this._getElem(ELEM);
var targetElem = this._findTarget(elem);
var email = elem.value;
var regex = /^[-_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\.[a-zA-Z0-9]+$/
if (regex.test(email))
{
targetElem.className = "msg";
return true;
}
else
{
targetElem.innerHTML = "please enter a valid email address";
targetElem.className = "msgshow";
return false;
}
}
catch(e)
{
alert("Error in Validator() -> checkEmail(): " + e.message);
return false;
}
}
Here I create the object, and a email validation prototyped function. The function takes to arguments: an element, and an optional event. If an event is passed in, it is used to create a listener using the yahoo YUI library. This listener will fire on the given event, calling the same function without the optional argument (and thus running the validation).
The rest of the function is fairly straight forward. It first makes calls to getElem, and findTarget. if getElem is given a string, it returns the element with the given ID. If getElem is given an element, it simply returns the element. findTarget simply gets the ID of the passed in element, and appends ‘_error’, then gets the element with the new string ID.
From there is simply runs a regex expression, and if the regular expression matches it makes sure the error message is hidden, otherwise it sets the text and displays the error message.
This total solution is very portable and easy to use. After including the YUI libraries needed, and the validator code, one can add validation to an element by simply doing:
var validator = new Validator();
validator.checkEmail('email', 'change');
The only custom bit of code is two lines, and you have a regular expression checking the input field every time the field is changed, and will dynamically display an error message when incorrect.