Form validation can help to reduce the amount of bad data that gets saved to your database. In this article, find out how you can write a simple JavaScript form validator for basic client-side validation, and learn a little bit about JavaScript OOP in the process as well.
// create object
function formValidator()
{
// snip
}
Now, since I plan to build some basic error-handling routines into this class, I need to add a variable to hold this information.
// create object
function formValidator()
{
// set up array to hold error messages
this.errorList = new Array;
// snip
}
Let's now begin constructing the validation routines themselves.
Here's the first one, which performs a very basic test; it checks to see whether the corresponding variable contains a value or not.
// check to see if input is whitespace only or empty
function isEmpty(val)
{
if (val.match(/^s+$/) || val == "")
{
return true;
}
else
{
return false;
}
}
This is fairly simple, but worth examining in detail, since all subsequent methods will follow a similar structure.
The isEmpty()method is called with a single argument: the value to be tested. It then uses the match() method of the JavaScript String object to check this value against a regular expression. In this specific example, the regular expression is designed to match a string consisting of spaces only; such a string can reasonably be considered "empty" of any actual data. If such a string is found, or if the value is found to contain nothing, the function returns true; if not (that is, if the value actually contains some data), the function returns false.
As you will see, this type of structure for the object method makes it simple to wrap the method call in a conditional test in your form processing script.
Let's move on to another interesting function:
// check to see if input is number
function isNumber(val)
{
if (isNaN(val))
{
return false;
}
else
{
return true;
}
}
In this case, the JavaScript isNaN() function is used to check whether the value supplied to it is a number or not.
Another useful method, especially when dealing with numbers, is theisWithinRange() method, which provides an easy way to check whether the input is within a certain numeric range.
// check to see if value is within min and max
function isWithinRange(val, min, max)
{
if (val >= min && val <= max)
{
return true;
}
else
{
return false;
}
}
Finally, you can include a small method to verify if a particular checkbox is checked or not, via the isChecked() method:
// check to see if form value is checked
function isChecked(obj)
{
if (obj.checked)
{
return true;
}
else
{
return false;
}
}
Note the difference between this method, and the ones that preceded it. Previous object methods have been written to accept a form value as argument; this one accepts an object, representing the checkbox element, as argument.