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.
In order to illustrate how form validation typically works, consider the following simple example:
<html>
<head>
<basefont face="Arial">
<script language="JavaScript">
function validateForm()
{
// check name
if (document.forms[0].elements[0].value == "")
{
alert ("Please enter a name!");
return false;
}
// check password length
if (document.forms[0].elements[1].value.length < 6)
{
alert ("Please enter a password
of at least 6 characters!");
return false;
}
// check email address
// check age
if (isNaN(document.forms[0].elements[3].value))
{
alert ("Please enter a valid age!");
return false;
}
// check age range
if (parseInt(document.forms[0].elements[3].value) < 1 ||
parseInt(document.forms[0].elements[3].value) > 99)
{
alert ("Please enter a valid age!");
return false;
}
return true;
}
</script>
</head>
<body>
<form action="someform.cgi" method="post"
onSubmit="return validateForm();">
Name:
<br>
<input type="text" name="name" id="name">
<p>
Password:
<br>
<input type="password" name="password" id="password">
<p>
Email address:
<br>
<input type="text" name="email" id="email">
<p>
Age:
<br>
<input type="text" name="age" id="age">
<p>
<input type="submit" value="Submit Form">
</form>
</body>
</html>
This is a simple form, with fields for the user to enter his or her name, a password, an email address, and an age value. Before the form is submitted, the "onSubmit" event handler calls the validateForm() function, which checks that
a name is present;
the length of the password is 6 or more characters;
the email address is in a valid format;
the age value is a number, and in the range 1-99.
If any of these tests fail, the validateForm() function will print an error message and return false, which will prevent the form from being submitted. Only after all the validation tests are successfully passed will the function return true and allow the form submission to proceed. In this manner, basic client-side validation can prevent incorrect data from slipping through into your database.
Since this kind of client-side validation is a fairly common task in the Web development world, it's a good idea to encapsulate some of the more common tasks in this context into reusable functions, which can be called as and when needed in your scripts, so as to reduce time and effort spent in this aspect of Web application development. The cleanest way to do this is to build a simple JavaScript form validation object, and add methods to it to validate different types of data. Let's look at that next.