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

JavaScript form validations made easy

By , 22 Nov 2001
 

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

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionAsp.netmemberS4nd1p23 Apr '13 - 22:15 
Can i use this JavaScript in asp.net validation if it possible please give me a example
Questionjquery questiongrouplakshmisindhu4 Apr '12 - 19:29 
I need a jquery function to validate my textbox value.
 
Requirement: required filed:true, minlength:8, maxlength:16, should allow only alphabets, numbers.
 
i have written one function:
 
jQuery.validator.addMethod("nameRegex", function (value) {
         //   alert(value);
            if (value.length >= 8) {
               // alert(value.length);
                        return value.match(/^[a-zA-Z0-9 ]+$/.test(value));
            }
      }, "Contain only letters, numbers.");
but this is not working can any one pls help me in this.
 
-Sindhu.A
GeneralForm submit to servermemberAjay Kale New18 Oct '10 - 20:42 
Hi ,
 
I am submitting a html form in ASP.NET 1.1, to a websphere server. I am browsing excel file and submitting through object to Websphere server, by sybmitting form with action as Websphere hosted address.
 
Whenever I login to app, and try to upload the file with above functionality, for the first time, I get redirected to Login.aspx automatically. But when I re-login again and does the same thing as above, the file is uploaded successfully.
 
Can you please help me regarding this, as I have maintained releative values of timeout for session and form-authentication in web.config file.
 
- Ajay K
Generalnid help usin this codememberlittle30 Mar '08 - 19:25 
<![CDATA[<%@ page contentType="text/html;charset=UTF-8" language="java" %>]]>
<![CDATA[<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>]]>
 

Log In

 
<form action="loginComponent.jsp" focus="username">
 
<!-- username and password -->
 
 
<!-- Login button-->
Username: <input type="text">
name="username" maxlength="20" size="20"
value="" /></input>
Password: <input type="password">
name="password" maxlength="20" size="20"
value="" /></input>

<input type="submit">
name="login"
value="Log In" />
</input>
</form>

Username is "user", password is "pass".


GeneralNew Validation Descriptor to Confirm Password or any other value [modified]memberGennady@GA7 Mar '07 - 10:55 
Thank you, Prasanth
For the very helpful JavaScript.
 
As of my feeling we need at least one more validation descriptor - "confirm",
that will confirm passwords or any other values.
This descriptor will apply to the 2nd value field ( Password confirm: ) and will use value from the previous field ( Password: ) to compare both of them.
 
I'm publishing modifications to the code below. Please add them to your original file available for download.
 
Thank you,
Gennady
 

Modifications to gen_validation.js:
 
1. Change this code in line 54 from:
 
function validateData(strValidateStr,objValue,strError)
 
to:
 
function validateData(strValidateStr,objValue,strError,objValuePrev)

 
2. Add this code to the end of switch operator in function validateData - just before "}//switch" (line 240):
 

case "confirm":
{
if(objValue.value != objValuePrev.value)
{
if(!strError || strError.length ==0)
{
strError = objValue.name+": Value was not correctly confirmed";
}//if
alert(strError);
return false;
}//if
break;
}//case confirm
 

3. in function validateForm change body of this for operator
 
for(var itrdesc=0; itrdesc < arrObjDesc[itrobj].length ;itrdesc++)
 
from:
 
{
if(validateData(arrObjDesc[itrobj][itrdesc][0],
objFrm[itrobj],arrObjDesc[itrobj][itrdesc][1]) == false)
{
objFrm[itrobj].focus();
return false;
}//if
}//for
 

to:
 
{
if(itrobj >= 0)
{
if(validateData(arrObjDesc[itrobj][itrdesc][0],
objFrm[itrobj],arrObjDesc[itrobj][itrdesc][1],objFrm[itrobj-1]) == false)
{
objFrm[itrobj].focus();
return false;
}//if
}
else
{
if(validateData(arrObjDesc[itrobj][itrdesc][0],
objFrm[itrobj],arrObjDesc[itrobj][itrdesc][1],0) == false)
{
objFrm[itrobj].focus();
return false;
}//if
}//if
}//for
 
THE END!
 
-- modified at 22:07 Wednesday 7th March, 2007
QuestionValidate password charactersmemberZafar Nadeem20 Sep '06 - 16:32 
Hi, I am new to JavaScript and I am trying to control New Password fields. These fields are not allowed to except any symbols, especially @/\. The current code I've is not working at at all. Could someone help please.
 

function changepass_submit()
{
if (document.Eform.USERNAME.value=="") {
alert("Please Enter Value for Username");
document.Eform.USERNAME.focus();}
else if (document.Eform.PASSWORD.value=="") {
alert("Please Enter Value for Password");
document.Eform.PASSWORD.focus();}
else if (document.Eform.NEW_PASSWORD.value=="") {
alert("Please Enter Value for New Password");
document.Eform.NEW_PASSWORD.focus();}
else if (document.Eform.NEW_PASSWORD.value=="@" || document.Eform.NEW_PASSWORD.value=="/" || document.Eform.NEW_PASSWORD.value=="&" || document.Eform.NEW_PASSWORD.value=='"') {
alert("Please Enter Value for New Password");
document.Eform.NEW_PASSWORD.focus();}
else if (document.Eform.CONFIRM_PASSWORD.value=="") {
alert("Please Enter Value for Confirm Password");
document.Eform.CONFIRM_PASSWORD.focus();}
else if (document.Eform.CONFIRM_PASSWORD.value!=document.Eform.NEW_PASSWORD.value) {
alert("Please Re-enter New Password/Confirm Password...New Password is not the same as Confirm Password");
document.Eform.CONFIRM_PASSWORD.focus();}
else
{ document.Eform.submit() }
}
</script>
 
Many thanks.
GeneralAdvanced field validation help neededmemberdevelopmentbox12 Jul '06 - 22:47 
Hello,
 
I have a form that has a field for an approval code. The idea is to have it work like a passcode field and the form would only be submitted if the approval code entered matches one listed in an access table.
 
I already have a basic function to verify the field is not empty and return an alert if it is empty.
 
Would anyone have a good javascript function that would take the input, compare it to list of codes in an access table field, and return false if the input does not match?
 
I know how to do this on the server side but have no idea how to do this on the client side with javascript, or maybe I am looking at it wrong.
 
Thanks,
 
Wayne.
QuestionChanging Html Combo Box Selection to Original StatememberJany_2k9 Jun '06 - 20:20 
I m working on a scenario in which if user changes a selection in one of the the drop downs avaiable on html form then a warning message is displayed with yes and no option. In case user opts for "No" then i have to change the combo box selection to previously selected item.
I have tried using OnChange Event but this event fires after making the changes but not before making these changes. Is there any way of handling before selection event in Javascript
 
Thanks
QuestionCookies - I'm confused!!!memberSmallishfry24 Oct '05 - 6:21 
Cookies - I'm confused!!! I know there must be a script that can be run on an apache server which will allow my visitors, once successfully logged in, to stay logged in until they log out! I'm having problems...
 
Anyway, thanks in advance all you random strangers! Big Grin | :-D
 
Smallishfry@hotmail.co.uk
 
Smile | :) E-mail me if your willing to pay for a professional we-page at the fraction of a cost.
GeneralJavascript errormemberd2_sos20 Sep '05 - 12:22 
I am kind of new to programming javascript, and I keep getting this error: "Line: 28, Char: 18, Error: Expected "]", Code: 0, URL: my url"
 
Here is the code:
<SCRIPT language="JavaScript1.2">
var arrFormValidation=
[
[//Name:
["req"],
["maxlen="20"],
["minlen=1"],
["alpha"],

],
 
[//E-mail:
["req"],
["maxlen=50"],
["minlen=1"],
["email"],
],


 

[//Age:
["req"],
["maxlen=2"],
["minlen=2"],
],
[//Location:
["req"],
["minlen=3"],
["maxlen="30"],
 
],
 
[//Acct:
["req"]
],
 
[//Why Join:
["req"],
["minlen="10"],
["maxlen="100"],
 
];
Any idea what I am doing wrong? Help is much appreciated.

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

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