Click here to Skip to main content
15,895,667 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.7K   3.4K   64  
Using JavaScript to make form validation fast and easy
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<title>Easy Form Validation : How to use it</title>
<Style>
BODY, P,TD{ font-family: Arial,Verdana,Helvetica, sans-serif; font-size: 10pt }
</Style>
</head>
<body>
<center>
<A name="top"></A>
<table cellspacing="2" cellpadding="2" border="0" width="520px">
<tr><td>
<HR>
<H2>Form Validations Made Easy</H2>
<h4>Documentation</h4>
<HR>
Contributed by:<BR>
<A href="mailto:prasanth@creativeprogrammers.com">Prasanth M J</A><BR>
CreativeProgrammers.com <BR>
Turn your Programming Expertise into Achievements!<BR>
Visit <A target="_blank" href="http://www.creativeprogrammers.com">http://www.creativeprogrammers.com</A> Now
<hr align=left width=320>
<BR><BR>
<B>Index</B><BR>
	<A href="#example">A simple example</A><BR>
	<A href="#customerr">Giving custom error messages</A><BR>
	<A href="#complexfrm">Handling more complex forms</A><BR>
	<A href="#tabledesc">The table of descriptors</A><BR>
	<P>
	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.
	</P> 
	<P>
	A java script function is presented here, which makes form validation easier. 
	</P>
	<P>
	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.
	</P>
	<P>
	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
	</P>
	<P>
	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. 
	</P>
	<P>
	Let us see how can this function be used to ease form validation.
	</P>
	<P>
	The function syntax is like this: <BR>
	 validateForm(formObject,arrValidationDesc)<BR>
	  formObject is the form which should be validated.<BR>
	  arrValidationDesc is the array containing the validation descriptors for each input item.
	</P>
	<A name="example"></A>
	<P><A href="#top">Back to Top</A></P>
	<P>
	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. 
	</P>
	
	The code goes like this:<BR><BR>
	
	&lt;SCRIPT language="JavaScript1.2" src="gen_validation.js"&gt;&lt;/SCRIPT&gt; <BR>
	<BR>
	&lt;SCRIPT language="JavaScript1.2"&gt;<BR>
	<BR>
	// The array of validation definitions <BR>
	<BR>
	arrValidationDesc=<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &nbsp;<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &nbsp; // Validations for the login name field <BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["required"], // Validation 1 : It is a required field<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25"] &nbsp;// Validation 2: Max number of characters 25<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ // validations for the password field<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["minlen=5"],// validation 1 : 5 chars minimum<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25"] // validation 2 : 25 chars maximum<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]; <BR>
	<BR>
	&lt;/SCRIPT&gt; <BR>
	<BR>
	<BR>
	<BR>
	Now, the form, <BR>
	<BR>
	<BR>
	&lt;FORM onsubmit="return validateForm(this,arrValidationDesc);"&gt;<BR>
	<BR>
	LoginName: &lt;input type="text" name="LoginName"&gt; &lt;BR&gt;<BR>
	<BR>
	Password : &lt;input type="password" name="password"&gt; &lt;BR&gt;<BR>
	<BR>
	&lt;input type="submit" value="Submit"&gt;<BR>
	<BR>
	&lt;/FORM&gt;<BR>
	
	<P>
	and that�s it! 
	</P>
	<P>
	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.
	</P>
	<P>
	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.
	</P>
	<A name="customerr"></A>
	<P><A href="#top">Back to Top</A></P>
	<P>
	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 
	</P>
	<BR>
	"LoginName: Required field."<BR>
	<P>
	That too, if the name of the input text element is given as "LoginName"
	</P>
	<P>
	It is possible to give your own error messages. The example below shows the code 
	modified to contain the custom error messages
	</P>
	<BR>
	&lt;SCRIPT language="JavaScript1.2"&gt;<BR>
	<BR>
	// The array of validation definitions<BR>
	<BR>
	arrValidationDesc=<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &nbsp;// Validations for the login name field<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["required",<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Did you forget to enter your login name, my dear friend?"], <BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25", "Too long login name ??"] &nbsp;<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ // validations for the password field<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["minlen=5"," Password should contain 5 chars minimum"],<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25"] <BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]; <BR>
	<BR>
	&lt;/SCRIPT&gt; <BR>
	
	<BR>
	The rest is the same.<BR>
	<BR>
	<P>
	In general, the format of the validation description is:
	</P>
	
	arrayname=<BR>
	 &nbsp; &nbsp; &nbsp; [<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ // Validations for input item 1<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &lt;validation_descriptor&gt;, &lt;error_string&gt;]<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &lt;validation_descriptor&gt;, &lt;error_string&gt;]<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ......<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ......<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ // Validations for input item 2<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &lt;validation_descriptor&gt;, &lt;error_string&gt;]<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &lt;validation_descriptor&gt;, &lt;error_string&gt;]<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ......<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ......<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .................<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .................<BR>
	 &nbsp; &nbsp; &nbsp; ];<BR>
	<BR>
	
	<P>
	As you saw, the &lt;error_string&gt; is optional.
	</P>
	<P>
	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.
	</P>
	<P>
	What if a particular field doesn't have any validations? Just add a null 
	record like this:
	</P>
	<BR>
	<BR>
	&lt;SCRIPT language="JavaScript1.2"&gt;<BR>
	<BR>
	// The array of validation definitions<BR>
	<BR>
	<BR>
	arrValidationDesc=<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &nbsp;<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ &nbsp;// Validations for the first field<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["required"], <BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25"] &nbsp;<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ ], // the second field doesn't have any validations<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ // validations for the third field<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["minlen=5"],<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25"] <BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]; <BR>
	<BR>
	&lt;/SCRIPT&gt; <BR>
	
	<P>
	The validation descriptor records should be in the order of the corresponding fields in 
	the form.
	</P>
	<A name="complexfrm"></A>	
	<P><A href="#top">Back to Top</A></P>
	<P>
	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:
	</P>
	
	&lt;SCRIPT language="JavaScript1.2"&gt;<BR>
	<BR>
	arrValidationDesc= new Array();<BR>
	idx = 0;<BR>
	<BR>
	&lt;/SCRIPT&gt; <BR>
	<BR>
	&lt;form onSubmit="return validateForm(this,arrValidationDesc);"&gt;<BR>
	<BR>
	LoginName: &lt;input type="text" name="LoginName"&gt; <BR>
	<BR>
	&lt;SCRIPT language="JavaScript1.2"&gt;<BR>
	<BR>
	// validation description for Login Name<BR>
	<BR>
	arrValidationDesc[idx++] =<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["required","Please enter Login Name"], <BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25","Login Name too long! "] &nbsp;<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;];<BR>
	&lt;/SCRIPT&gt; <BR>
	<BR>
	Password : &lt;input type="password" name="password"&gt; <BR>
	<BR>
	&lt;SCRIPT language="JavaScript1.2"&gt;<BR>
	// validation description for password<BR>
	<BR>
	arrValidationDesc[idx++] = <BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["minlen=5"], &nbsp;<BR>
	<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["maxlen=25"] &nbsp;<BR>
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;];<BR>
	&lt;/SCRIPT&gt; <BR>
	&lt;input type="submit" value="Submit"&gt;<BR>
	&lt;/FORM&gt;<BR>
</td></tr>
</table>
	<A name="tabledesc"></A>	
	<P><A href="#top">Back to Top</A></P>
<H3>Table: The Validation Descriptors</H3>
<TABLE border=1 cellPadding=2 cellSpacing=2 width=520>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>maxlen=???<BR>maxlength=???</FONT> 
    </TD>
    <TD><FONT face=Arial size=2>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"</FONT> </TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>minlen=???<BR>minlength=???</FONT> 
    </TD>
    <TD><FONT face=Arial size=2>Check the length of the entered data with the 
      required minimum. Example "minlen=5"</FONT> </TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>required<BR>req </FONT></TD>
    <TD><FONT face=Arial size=2>Raise error if the field is left empty.</FONT></TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>email </FONT></TD>
    <TD><FONT face=Arial size=2>The field is an email field and verify the 
      validity of the data. </FONT></TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>alphanumeric <BR>alnum </FONT></TD>
    <TD><FONT face=Arial size=2>Check the data if it contains any 
      characters other than alpahbetic or numeric characters </FONT></TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>num <BR>numeric </FONT></TD>
    <TD><FONT face=Arial size=2>Check numeric data </FONT></TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>alpha <BR>alphabetic </FONT></TD>
    <TD><FONT face=Arial size=2>Check alphabetic data. </FONT></TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>lt=???<BR>lessthan=???</FONT> </TD>
    <TD><FONT face=Arial size=2>Verify the data to be less than the value 
      passed. Valid only for numeric fields. <BR>Example: if the value should be 
      less than 1000, give validation descriptor as "lt=1000"</FONT> </TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>gt=???<BR>greaterthan=???</FONT> 
</TD>
    <TD><FONT face=Arial size=2>Verify the data to be greater than the value 
      passed. Valid only for numeric fields. <BR>Example: if the value should be 
      greater than 10, give validation descriptor as "gt=10" </FONT></TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>regexp=??? </FONT></TD>
    <TD><FONT face=Arial size=2>Check with a regular expression; the data entered 
      should match the regular expression.<BR>Example: "regexp=^[A-Za-z]{1,20}$" 
      allow up to 20 alphabetic characters.</FONT> </TD></TR>
  <TR>
    <TD vAlign=top><FONT face=Arial size=2>dontselect=?? </FONT></TD>
    <TD><FONT face=Arial size=2>This validation descriptor is valid only for 
      &lt;SELECT&gt; 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"</FONT> 
</TD></TR></TABLE>
<P><A href="#top">Back to Top</A></P>
</center>

</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


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