JavaScript Form Validation

Source Code Back to Tutorials

The form on this page is for showing form validation techniques.
If you enter inappropriate data in the fields on this page you will immediately be prompted to correct it.

Validation Rules in place are:
1. Start Date must be a valid date.
2. End Date must be a valid date.
3. End Date must be equal to or later than Start Date.
4. Number must be a valid number between 1 and 10

 

Start Date:
(MM/DD/YYYY) Will cause error if not a date value (try and see)
End Date:
(MM/DD/YYYY) Will cause error if not a date value (try and see)
Number:
Only Numbers 1 - 10 are valid here.

When validating dates it is important to understand that the format of the date is very important.  For example if we expect a date to be entered in MM-DD-YYYY format then 06/30/2004 is a valid date.  However if we expect the date to be entered in DD-MM-YYYY  format then the same value would be invalid.  In our ASP example the validation happens on the server and uses the server's settings to determine date format.  With JavaScript we will control what format or formats we are looking for.  This is an important concept when working on sites that will be accessed by people who's standard date format may be different from what is the standard at the server.

Although the JavaScript version is considerably more complex, it has the advantage that the information is validated immediately on entry rather than after the fact.  The user will know they have made a mistake immediately rather than filling out an entire form and then being told of their mistake after the fact.  The JavaScript method also allows you to place the user back in the correct field to fix their mistakes.

In order to perform the validation we used the onBlur event of the textboxes.  This works well enough, but it is possible to still enter the incorrect data and immediately submit the form by using the Enter key.  To prevent this we use the onSubmit function of the form.  We could simply use the onSubmit function and not the onBlur function, but that would remove our immediate response to erroneous entries.