Click here to Skip to main content
Click here to Skip to main content

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

Introduction

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

arrValidationDesc=
                [  
                  [   // 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
                  ]
                ];

</SCRIPT>

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">

</FORM>


and that’s it!

Notice that gen_validation.js is the file which contains the source code for the form validation function validateForm(). The formwiz1.zip 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

arrValidationDesc=
            [
                  [  // Validations for the login name field

                      ["required",
                 "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"],

                      ["maxlen=25"]
                  ]
            ];

</SCRIPT>
The rest is the same.

The general format of Validation descriptors

In general, the format of the validation description is:

arrayname=
      [
          [ // 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


arrValidationDesc=
                [  
                  [  // Validations for the first field

                      ["required"],

                      ["maxlen=25"]  
                  ],

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

                  [ // validations for the third field

                      ["minlen=5"],

                      ["maxlen=25"]
                  ]
                ];

</SCRIPT>

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;

</SCRIPT>

<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! "]  
              ];
</SCRIPT>

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

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

arrValidationDesc[idx++] =
              [
                  ["minlen=5"],  

                  ["maxlen=25"]  
              ];
</SCRIPT>
<input type="submit" value="Submit">
</FORM>

Table: The Validation Descriptors

maxlen=???
maxlength=???
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"
minlen=???
minlength=???
Check the length of the entered data with the required minimum. Example "minlen=5"
required
req
Raise error if the field is left empty.
email The field is an email field and verify the validity of the data.
alphanumeric
alnum
Check the data if it contains any characters other than alpahbetic or numeric characters
num
numeric
Check numeric data
alpha
alphabetic
Check alphabetic data.
lt=???
lessthan=???
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"
gt=???
greaterthan=???
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"

License

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

Share

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.

Comments and Discussions

 
GeneralForm submit to server PinmemberAjay Kale New18-Oct-10 21:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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
Web03 | 2.8.141216.1 | Last Updated 23 Nov 2001
Article Copyright 2001 by Prasanth M J
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid