JavaScript Page 6 - Form Validation with JavaScript |
So that's the theory. Let's now spend a few minutes discussing the rationale behind the formValidator object I plan to build. Stripped down to its bare bones, my formValidator object consists of twocomponents:
As you will see, these two basic components make it possible to build a very simple (and yet very useful) formValidator object, one that exposes a number of generic methods. Now, before proceeding further, I need to decide how this class is going to work. Here's how I plan to use it:
// instantiate object
fv = new formValidator();
// perform checks
// check for empty field
if (fv.isEmpty(document.forms[0].elements[0].value))
{
fv.raiseError("Please enter a value");
}
// check for field range
if (!fv.isWithinRange(document.forms[0].elements[1].value, 1, 99))
{
fv.raiseError("Please enter a value in the range 1-99");
}
// if errors, display, else proceed
if (fv.numErrors() > 0)
{
fv.displayErrors();
}
As you can see, once the object is instantiated, various object methods are called (with the appropriate form input value as parameter) to test whether the input is "good." If it isn't, an error is raised and stored in the object's internal error stack; these errors can be displayed at a later time, once all the validation is complete. Once the basic functionality of the object is clear, it's a good idea to spend some time listing the important methods, together with their purpose. Here's my initial cut:
These are the essential methods; there may be more, which I will add as development progresses.
blog comments powered by Disqus |