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">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.
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;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++) {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.