Click here to Skip to main content
11,930,231 members (43,113 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


61 bookmarked

JavaScript form validations made easy

, 22 Nov 2001
Rate this:
Please Sign up or sign in to vote.
Using javascript to make form validation fast and easy
<!-- Download Links --> <!-- Main HTML starts here -->


Using client side JavaScript is an efficient way to validate the user input in web applications. When there are many fields in the form, the JavaScript validation becomes too complex.

A java script function is presented here, which makes form validation easier.

The idea is to create a set of "validation descriptors" associated with each element in a form. The "validation descriptor" is nothing but a string specifying the type of validation to be performed.

Each field in the form can have 0, 1, or more validations. For example, the input should not be empty, should be less than 25 chars, should be alpha-numeric, etc

Therefore, each field in the form may be having an array of validations associated. The validation function takes such an array of arrays, each representing the validation to be performed on each of the input items in the form.

Let us see how this function can be used to ease form validation.

The function syntax is like this

  • validateForm(formObject,arrValidationDesc)
  • formObject is the form which should be validated.
  • arrValidationDesc is the array containing the validation descriptors for each input item.

A simple example

Let us take a login form as an example. Here, the login name and password are the input fields. The login name is a required field. The maximum length of login name is 25. The password should contain 5 characters minimum and 25 characters maximum.

The code goes like this:

<SCRIPT language="JavaScript1.2" src="gen_validation.js"></SCRIPT>

<SCRIPT language="JavaScript1.2">

// The array of validation definitions

                  [   // Validations for the login name field

                      ["required"], // Validation 1 : It is a required field

                      ["maxlen=25"]  // Validation 2: Max number of characters 25

                  [ // validations for the password field

                      ["minlen=5"],// validation 1 : 5 chars minimum

                      ["maxlen=25"] // validation 2 : 25 chars maximum


Now, the form,

<FORM onsubmit="return validateForm(this,arrValidationDesc);">

LoginName: <input type="text" name="LoginName"> <BR>

Password : <input type="password" name="password"> <BR>

<input type="submit" value="Submit">


and that’s it!

Notice that gen_validation.js is the file which contains the source code for the form validation function validateForm(). The file contains this file.

When the user presses the submit button, the onsubmit event will be triggered, which will call the validation function, passing the form object and the validation descriptions. If the user enters invalid data, or if the required fields are empty, an error message will be displayed and the validation function will return false. This will prevent the form from being submitted.

But, the Error message may not be descriptive enough as you like it to be. If the user didn't enter the login name, for example, the error message displayed will be

"LoginName: Required field."

That too, if the name of the input text element is given as "LoginName"

It is possible to give your own error messages. The example below shows the code modified to contain the custom error messages

<SCRIPT language="JavaScript1.2">

// The array of validation definitions

                  [  // Validations for the login name field

                 "Did you forget to enter your login name, my dear friend?"],
                      ["maxlen=25", "Too long login name ??"]  

                  [ // validations for the password field

                      ["minlen=5"," Password should contain 5 chars minimum"],


The rest is the same.

The general format of Validation descriptors

In general, the format of the validation description is:

          [ // Validations for input item 1

              [ <validation_descriptor>, <error_string>]

              [ <validation_descriptor>, <error_string>]

          [ // Validations for input item 2

              [ <validation_descriptor>, <error_string>]

              [ <validation_descriptor>, <error_string>]



As you saw, the <error_string> is optional.

It is important to keep in mind that the order of the input items in the array and the order in the form should be the same.

Fields without any validations

What if a particular field doesn't have any validations? Just add a null record like this:

<SCRIPT language="JavaScript1.2">

// The array of validation definitions

                  [  // Validations for the first field



                  [ ], // the second field doesn't have any validations

                  [ // validations for the third field




Handling complex validations

The validation descriptor records should be in the order of the corresponding fields in the form.

It may be difficult to keep track of the order in large forms. So, here is an easier way. Declare the array before the form tag. Add the descriptors for each input field just under the input field. Like this:

<SCRIPT language="JavaScript1.2">

arrValidationDesc= new Array();
idx = 0;


<form onSubmit="return validateForm(this,arrValidationDesc);">

LoginName: <input type="text" name="LoginName">

<SCRIPT language="JavaScript1.2">

// validation description for Login Name

arrValidationDesc[idx++] =
                 ["required","Please enter Login Name"],

                 ["maxlen=25","Login Name too long! "]  

Password : <input type="password" name="password">

<SCRIPT language="JavaScript1.2">
// validation description for password

arrValidationDesc[idx++] =

<input type="submit" value="Submit">

Table: The Validation Descriptors

Check whether the length of the data exceeds the allowed maximum. For example, if the maximum size permitted is 25, give the validation descriptor as "maxlen=25"
Check the length of the entered data with the required minimum. Example "minlen=5"
Raise error if the field is left empty.
email The field is an email field and verify the validity of the data.
Check the data if it contains any characters other than alpahbetic or numeric characters
Check numeric data
Check alphabetic data.
Verify the data to be less than the value passed. Valid only for numeric fields.
Example: if the value should be less than 1000, give validation descriptor as "lt=1000"
Verify the data to be greater than the value passed. Valid only for numeric fields.
Example: if the value should be greater than 10, give validation descriptor as "gt=10"
regexp=??? Check with a regular expression; the data entered should match the regular expression.
Example: "regexp=^[A-Za-z]{1,20}$" allow up to 20 alphabetic characters.
dontselect=?? This validation descriptor is valid only for <SELECT> input items (lists). Normally, the select list boxes will have one item saying 'Select One'. The user should select an option other than this option. If the index of this option is 0, the validation descriptor should be "dontselect=0"


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Prasanth M J
Web Developer
India India
Prasanth is the author of JSCoder - a tool for generating HTML forms, form validations, popup windows etc quickly and easily.

You may also be interested in...

Comments and Discussions Pin
S4nd1p23-Apr-13 23:15
memberS4nd1p23-Apr-13 23:15 
Can i use this JavaScript in validation if it possible please give me a example
Questionjquery question Pin
lakshmisindhu4-Apr-12 20:29
grouplakshmisindhu4-Apr-12 20:29 
GeneralForm submit to server Pin
Ajay Kale New18-Oct-10 21:42
memberAjay Kale New18-Oct-10 21:42 
Generalnid help usin this code Pin
little30-Mar-08 20:25
memberlittle30-Mar-08 20:25 
GeneralNew Validation Descriptor to Confirm Password or any other value [modified] Pin
Gennady@GA7-Mar-07 11:55
memberGennady@GA7-Mar-07 11:55 
QuestionValidate password characters Pin
Zafar Nadeem20-Sep-06 17:32
memberZafar Nadeem20-Sep-06 17:32 
GeneralAdvanced field validation help needed Pin
developmentbox12-Jul-06 23:47
memberdevelopmentbox12-Jul-06 23:47 
QuestionChanging Html Combo Box Selection to Original State Pin
Jany_2k9-Jun-06 21:20
memberJany_2k9-Jun-06 21:20 
QuestionCookies - I'm confused!!! Pin
Smallishfry24-Oct-05 7:21
memberSmallishfry24-Oct-05 7:21 
GeneralJavascript error Pin
d2_sos20-Sep-05 13:22
memberd2_sos20-Sep-05 13:22 
QuestionValidating 2 controls? Pin
toticow28-Jun-05 6:08
membertoticow28-Jun-05 6:08 
Generaljava script Pin
chopparasweety22-Jun-05 21:11
memberchopparasweety22-Jun-05 21:11 
Generalpassword validation Pin
Anonymous8-Apr-05 15:29
sussAnonymous8-Apr-05 15:29 
GeneralRe: password validation Pin
drewbuckles13-Apr-05 8:04
memberdrewbuckles13-Apr-05 8:04 
GeneralSimple validation Pin
Anonymous6-Apr-05 6:29
sussAnonymous6-Apr-05 6:29 
GeneralPassword Validation using java scripts Pin
Sanfooora4-Jan-05 6:16
sussSanfooora4-Jan-05 6:16 
GeneralRe: Password Validation using java scripts Pin
Anonymous8-Jan-05 8:52
sussAnonymous8-Jan-05 8:52 
GeneralRe: Password Validation using java scripts Pin
kameshwarrao6-Apr-05 2:36
susskameshwarrao6-Apr-05 2:36 
GeneralRe: Password Validation using java scripts Pin
Anonymous13-Jun-05 4:27
sussAnonymous13-Jun-05 4:27 
GeneralUrgent Pin
Anonymous4-Oct-04 4:20
sussAnonymous4-Oct-04 4:20 
GeneralRe: Urgent Pin
Antonio Chagoury14-Dec-04 4:57
sussAntonio Chagoury14-Dec-04 4:57 
GeneralConvert certain charaters in textboxes Pin
magpulse25-Aug-04 7:59
membermagpulse25-Aug-04 7:59 
GeneralRe: Convert certain charaters in textboxes Pin
drewbuckles13-Apr-05 6:31
memberdrewbuckles13-Apr-05 6:31 
Generalvalidation Pin
silver_sand138-Aug-04 18:53
susssilver_sand138-Aug-04 18:53 
GeneralRe: validation Pin
Prasanth M J8-Aug-04 21:35
memberPrasanth M J8-Aug-04 21:35 
GeneralRe: validation Pin
Anonymous21-Jul-05 5:37
sussAnonymous21-Jul-05 5:37 
GeneralValidating List Pin
barleyman00717-Jun-04 6:50
memberbarleyman00717-Jun-04 6:50 
Generaljust a note Pin
Hockey21-May-04 20:42
memberHockey21-May-04 20:42 
GeneralRe: just a note Pin
Prasanth M J8-Aug-04 21:51
memberPrasanth M J8-Aug-04 21:51 
Generalalphabetic and spaces Pin
masquerade1618-Sep-03 14:43
membermasquerade1618-Sep-03 14:43 
GeneralRe: alphabetic and spaces Pin
Anonymous17-Jun-04 7:09
sussAnonymous17-Jun-04 7:09 
GeneralRe: alphabetic and spaces Pin
drewbuckles13-Apr-05 7:19
memberdrewbuckles13-Apr-05 7:19 
General1223 Pin
Anonymous9-Feb-02 1:51
memberAnonymous9-Feb-02 1:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 23 Nov 2001
Article Copyright 2001 by Prasanth M J
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid