Click here to Skip to main content
15,879,326 members
Articles / Programming Languages / Javascript

JavaScript Form Validations Made Easy

Rate me:
Please Sign up or sign in to vote.
4.74/5 (23 votes)
22 Nov 20014 min read 331.2K   3.4K   64   33
Using JavaScript to make form validation fast and easy

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

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

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

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

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

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

HTML
<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 alphabetic 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.


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

 
QuestionAsp.net Pin
S4nd1p23-Apr-13 22:15
S4nd1p23-Apr-13 22:15 
Questionjquery question Pin
lakshmisindhu4-Apr-12 19:29
lakshmisindhu4-Apr-12 19:29 
GeneralForm submit to server Pin
Ajay Kale New18-Oct-10 20:42
Ajay Kale New18-Oct-10 20:42 
Generalnid help usin this code Pin
little30-Mar-08 19:25
little30-Mar-08 19:25 
GeneralNew Validation Descriptor to Confirm Password or any other value [modified] Pin
Gennady@GA7-Mar-07 10:55
Gennady@GA7-Mar-07 10:55 
QuestionValidate password characters Pin
Zafar Nadeem20-Sep-06 16:32
Zafar Nadeem20-Sep-06 16:32 
GeneralAdvanced field validation help needed Pin
developmentbox12-Jul-06 22:47
developmentbox12-Jul-06 22:47 
QuestionChanging Html Combo Box Selection to Original State Pin
Jany_2k9-Jun-06 20:20
Jany_2k9-Jun-06 20:20 
QuestionCookies - I'm confused!!! Pin
Smallishfry24-Oct-05 6:21
Smallishfry24-Oct-05 6:21 
GeneralJavascript error Pin
d2_sos20-Sep-05 12:22
d2_sos20-Sep-05 12:22 
QuestionValidating 2 controls? Pin
totig28-Jun-05 5:08
totig28-Jun-05 5:08 
Generaljava script Pin
chopparasweety22-Jun-05 20:11
chopparasweety22-Jun-05 20:11 
Generalpassword validation Pin
Anonymous8-Apr-05 14:29
Anonymous8-Apr-05 14:29 
I would like to validate the password after someone presses the submit button. This is my first time using javascript, so for me to validate, I have to manually define the password value. Unfortunately, this value shows up in the page source, which makes it pointless to login when everyone can see the username and password. Is there a different way to verify password, or a way to hide the validation code?
GeneralRe: password validation Pin
drewbuckles13-Apr-05 7:04
drewbuckles13-Apr-05 7:04 
GeneralSimple validation Pin
Anonymous6-Apr-05 5:29
Anonymous6-Apr-05 5:29 
GeneralPassword Validation using java scripts Pin
Sanfooora4-Jan-05 5:16
sussSanfooora4-Jan-05 5:16 
GeneralRe: Password Validation using java scripts Pin
Anonymous8-Jan-05 7:52
Anonymous8-Jan-05 7:52 
GeneralRe: Password Validation using java scripts Pin
kameshwarrao6-Apr-05 1:36
susskameshwarrao6-Apr-05 1:36 
GeneralRe: Password Validation using java scripts Pin
Anonymous13-Jun-05 3:27
Anonymous13-Jun-05 3:27 
GeneralUrgent Pin
Anonymous4-Oct-04 3:20
Anonymous4-Oct-04 3:20 
GeneralRe: Urgent Pin
Antonio Chagoury14-Dec-04 3:57
Antonio Chagoury14-Dec-04 3:57 
GeneralConvert certain charaters in textboxes Pin
magpulse25-Aug-04 6:59
magpulse25-Aug-04 6:59 
GeneralRe: Convert certain charaters in textboxes Pin
drewbuckles13-Apr-05 5:31
drewbuckles13-Apr-05 5:31 
Generalvalidation Pin
silver_sand138-Aug-04 17:53
susssilver_sand138-Aug-04 17:53 
GeneralRe: validation Pin
Prasanth M J8-Aug-04 20:35
Prasanth M J8-Aug-04 20:35 

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.