Javascript Tutorials
Introduction to AJAX
Javascript Form Validation
Javascript Fundamentals

Javascript Form Validation

Getting Started With Javascript Validation


We're going to use a guestbook as base in this example. We start with a simple html form then use a few javascript functions to validate data was properly entered.

<form method="post" action="submit.html" onSubmit="return guestbookFormCheck()" id="guestBook">
Name: <input type="text" name="NAME" id="NAME"><br>
Email: <input type="text" name="EMAIL" id="EMAIL"><br>
Message: <textarea name="MSG" id="MSG"></textarea>

This basic html form posts three fields into submit.html. The onSubmit attribute of the form tag calls our javascript check function and will submit or cancel the submission based on the return of the javascript checking function. We have three input fields NAME, EMAIL, and MSG. NAME and EMAIL are text fields and MSG is a textarea box.

Javascript Validation Control Function

<script language="javascript">
function gustbookFormCheck() {

var numChecks = 4;
var fields = new Array(numChecks-1);
var checks = new Array(numChecks-1);
var minlen = new Array(numChecks-1);
var regex = new Array(numChecks-1);

In the beginning of guestbookFormCheck() we set the control variables numChecks, fields, checks, menlen, and regex. numChecks is used to tell the script the number of checks there are. fields, checks, minlen, and regex are all arrays used to store the form and checking to be performed information. The only mandatory arrays that must be set are fields and checks. minlen and regex are only used when using certain checks to be described later.

fields[0] = guestBook.NAME;
checks[0] = 'ifValue';
fields[1] = guestBook.EMAIL;
checks[1] = 'isEmail';
fields[2] = guestBook.MSG;
checks[2] = 'isValue';
fields[3] = guestBook.MSG;
checks[3] = 'regex';
regex[3] = REGEX TO GO HERE

Here we declare the fields and checks to be performed. We are performing the ifValue check on NAME, the isEmail check on the EMAIL field and both the isValue and a regex function on the MSG field. Our regex here is used to check for bad words.

for (i=0; i<numChecks; i++) {

var fieldValue = fields[i];

switch (checks[i]) {
case 'ifValue':
var result = formNotEmpty(fieldValue);
case 'isEmail':
var result = formIsEmail(fieldValue);
case 'regex':
var result = regex[i].test(fieldValue.value);
if (result == false) {
return false;
return true;

This is the heart of running through the checks. This for loop parses through the arrays and uses a switch statement to determine which check to perform. If one of the checks returns false an alert box is displayed to the viewer with an error, and false is returned to the browser which cancels the form submission for the visitor to fix the problem.

 1 2  >> Javascript Check Form Field Functions
New Content