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.
It's also possible to create more complex validation routines using JavaScript's built-in support for regular expressions. Consider the next method, isAlphabetic(), which uses a regular expression to test whether all the characters in the input string are alphabets…
// check to see if input is alphabetic
function isAlphabetic(val)
{
if (val.match(/^[a-zA-Z]+$/))
{
return true;
}
else
{
return false;
}
}
… or whether the input string contains a combination of letters and numbers.
// check to see if input is alphanumeric
function isAlphaNumeric(val)
{
if (val.match(/^[a-zA-Z0-9]+$/))
{
return true;
}
else
{
return false;
}
}
This ability to use regular expressions to perform data validation comes in particularly handy when checking user-supplied email addresses for validity, as the very cool (and very useful) method isEmailAddress() demonstrates:
// check to see if input is a valid email address
function isEmailAddress(val)
{
if (val.match(/^([a-zA-Z0-9])+
([.a-zA-Z0-9_-])*
@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_
-]+)+/))
{
return true;
}
else
{
return false;
}
}