Home arrow JavaScript arrow Page 10 - Form Validation with JavaScript

A Quick Snack - JavaScript

javascriptForm 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.

  1. Form Validation with JavaScript
  2. Check Point
  3. Object Lessons
  4. Rock On
  5. Hammer Time
  6. How Things Work
  7. A Little Space
  8. Expressing Yourself
  9. Under Construction
  10. A Quick Snack
By: Nariman K, (c) Melonfire
Rating: starstarstarstarstar / 464
December 01, 2003

print this article


At this stage, I think I have enough building blocks to actually begin using this class to perform form input validation. Let's build a simple form, and also add the JavaScript to validate the data entered into it. Note that the form validation object created on the previous page is stored in the file "formValidator.js," which is read in near the top of the page.

<basefont face="Arial">
<script language="JavaScript" src="formValidator.js">
<script language="JavaScript">
// check form values
function checkForm()
// instantiate object
fv = new formValidator();
// perform checks
// check for empty name field
if (fv.isEmpty(document.forms[0].elements[0].value))
fv.raiseError("Please enter a name");
// check for empty age field
if (fv.isEmpty(document.forms[0].elements[1].value))
fv.raiseError("Please enter an age");
// check for valid age range
if (!fv.isWithinRange(document.forms[0].elements[1].value, 
1, 99))
fv.raiseError("Please enter an age in the 
range 1-99");
// check for empty email address
if (fv.isEmpty(document.forms[0].elements[5].value))
fv.raiseError("Please enter an email address");
// check for valid email address format
if (!fv.isEmpty(document.forms[0].elements[5].value) &&
fv.raiseError("Please enter a valid email address");
// check for checkbox
if (!fv.isChecked(document.forms[0].elements[6]))
fv.raiseError("Please indicate your agreement with 
this site's terms and conditions");
// all done
// if errors, display, else proceed
if (fv.numErrors() > 0)
return false;
return true;
<form action="action.cgi" method="POST" 
onSubmit="return checkForm()">
<input type="text" name="name" size="15">
<input type="text" name="age" size="2" maxlength="2">
<input type="Radio" name="sex" value="m" checked>Male
<input type="Radio" name="sex" value="f">Female
<b>Favourite sandwich type:
<select name="stype">
<option value="1">Thin crust
<option value="2">Thick crust
<option value="3">Toasted
<b>Email address:
<input type="text" name="email" size="25">
<input type="Checkbox" name="agree">
I agree to the terms and conditions of this site
<input type="Submit" name="submit" value="Save">

In this case, when the form is submitted, the "onSubmit" event handler invokes the checkForm() function, which instantiates a new object of the formValidator class. Once this object has been instantiated, all the validation routines defined earlier become available to the script as object methods, and can be used to test the various input values provided in the form.

Let's see if it works. Here's what happens when I try submitting the form with no fields filled in:

* Error: Please enter a name 
* Error: Please enter an age
* Error: Please enter an age in the range 1-99
* Error: Please enter an email address 
* Error: Please indicate your agreement with this 
site's terms and conditions

And here's what happens when I submit the form with incorrect data in the age field:

* Error: Please enter an age in the range 1-99

Only when all the errors have been corrected, and the user's input passes all the validation tests, will the function checkForm() return true and the form get submitted to the form processing script. In this way, input validation can prevent erroneous data from corrupting your database.

Of course, you can perform input validation without using an object (as demonstrated in the very first example in this article). However, developers typically perform pretty standard tasks when validating form input; instead of writing (and rewriting) the same code over and over for each of your projects, it makes more sense to create a simple, reusable library of functions, encapsulate them in an object, and plug that object into your forms as and when needed.

It's important to note that the object above is still fairly primitive. If you plan to use it in a live environment, you should modify it to include more stringent error checking. (I've omitted this in the example above to make the code a little easier to read and explain.) You might also want to add more validation methods to it as and when you need them, so to build a library that you can reuse over and over again, for different applications and requirements.

And that's about all for the moment. In this article, you expanded your knowledge of JavaScript's OOP capabilities by actually using all that theory to build something useful - a form validation widget which can be used to verify the data entered into an online form, and provide a way for you to take action in case the data entered by the user does not met your expectations.

If you're a stressed-out Web developer working on a Web site, a Web application or an embedded system, you might find this object a handy tool in your next development effort. If you're a novice programmer struggling to understand how OOP can make your life easier, I hope this article offered some pointers, as well as some illustration of how object-oriented programming works. And if you don't fit into either of those categories - well, I hope you found it interesting and informative, anyway.

See you soon!

Note: All examples in this article have been tested in Microsoft Internet Explorer 6. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article.

>>> More JavaScript Articles          >>> More By Nariman K, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Javascript for Beginners: An Introduction
- Introduction to JavaScript
- Adding Elements to a Tree with TreeView jQue...
- Using the Persist Argument in a TreeView jQu...
- Using Unique and Toggle in a TreeView jQuery...
- Using Event Delegation for Mouseover Events ...
- Using the Animate Option in a Treeview jQuer...
- Using HTML Lists with Event Delegation in Ja...
- Opened and Closed Branches on a TreeView jQu...
- Mouseover Events and Event Delegation in Jav...
- Creating a TreeView JQuery Hierarchical Navi...
- Event Delegation in JavaScript
- A Look at the New YUI Carousel Control
- Working with Draggable Elements and Transpar...
- Displaying Pinned Handles with Resizable Con...

Developer Shed Affiliates


Dev Shed Tutorial Topics: