Powerful Form Validation Using ASP
by Hojjat Salmasian
Introduction
Form validation is the procedure of evaluating the validity of values submitted by a user in a form. The procedure can be carried out on the client side, the server side, or both! What we are focusing on here is the server side validation process.
There are two approaches to form validation, as well as any other subject in web design: One is to prepare a good computer program (code) capable to find the errors of interest, and the other is to prepare a good design layout, to inform the user about the errors. A very common design layout for erroneous submitting is to show the form again, focusing on the trouble-making field of the form, for example by changing it's color to red.
I'm going to show you how to develop a form, asking the user for his/her name, address, phone number, and email address, and validate the "required" fields. I've tried to keep the code simple, while at the same time, making it easy to customize, so that you can easily change the code to meet your needs on many different forms.
Strategy
Our page consists of a form, the action property of which is set to the same page. When the form is submitted, it evaluates the uploaded data, if no mistakes are found it will go on and store them in a database or anything, else (i.e. if mistakes exist), it will show the form again, with a message about the error on the top of it. It uses CSS to colorize the field which need to be fixed. We will start with a simple example, then add more features to it.
Step one: Start code
Let's start with a one field form, and only check if the field is filled before the form is submitted. Let's take a look at the code first and then I'll tell you how it works:
<%@LANGUAGE="VBSCRIPT"%>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple Form Validation</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<style>
.errorMessage {
color : #F00;
}
.errorItem {
background : #F99;
}
</style>
<body>
<%
'=================================
'Variables
'=================================
dim errorMessage, badItem, inputArray() : badItem=-1
redim inputArray(50,2)
'=================================
'Get all what is submitted
'=================================
IF request.Form.Count > 0 THEN
execute("const numberOfFields =" & request.Form.Count)
execute("redim inputArray("&numberOfFields&",2)")
FOR i = 1 TO request.Form.Count
inputArray(i,1) = request.Form.Key(i)
inputArray(i,2) = request.Form.Item(i)
NEXT
validate
ELSEIF request.QueryString.Count > 0 THEN
execute("const numberOfFields =" & request.QueryString.Count)
execute("redim inputArray("&numberOfFields&",2)")
FOR i = 1 TO request.QueryString.Count
inputArray(i,1) = request.QueryString.Key(i)
inputArray(i,2) = request.QueryString.Item(i)
NEXT
validate
END IF
SUB validate
'=================================
'Check for empty fields
'=================================
FOR i = 1 TO numberOfFields
IF inputArray(i,2)="" THEN
badItem = i
errorMessage = "At least one of the required fields is left empty."
EXIT SUB
END IF
NEXT
END SUB
%>
<h2>Form Validator</h2>
<%
IF errorMessage<>"" THEN
%>
<p class="errorMessage">There was an error with your form: <b><%=errorMessage%></b></p>
<%
ELSEIF request.form.count = 0 THEN
%>
<h3>Please fill in the form:</h3>
<%
ELSE
%>
<h3>Thank you!</h3>
</body>
</html>
<%
Response.End
END IF
%>
<form action="default.asp" method="post">
<p>Name: <font color="#FF0000">*</font>
<input name="name" type="text" id="name" value="<%=inputArray(1,2)%>" <%IF badItem=1 THEN response.write
"class=""errorItem"""%>/>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
</body>
</html>
You aren't confused are you?! All right ... First we define some variables: errorMessage is a string variable which we later use to put our error message in it. badItem is a numeric variable containing the number of trouble making field. The number of fields start from ZERO, so we initialize the value of this variable to -1 (here: badItem=-1). And inputArray() is an array variable which will contain the submitted form items with their values. WHY DO WE USE THIS ARRAY? You will know that soon.
Now! Please be more careful about this part, or it is a bit difficult to understand. With the next few lines of code we are going to store all submitted data to inputArray() variable. We use a variable to avoid using several Request.Form or Request.QueryString lines in our code. The second benefit is, the code will automatically collect the submitted data, no matter how many fields there are, no matter it was sent with GET or POST, so we can use the code with other forms with very few changes.
An IF clause will check whether the form is submitted with GET or POST method. If none of them is true (form is not submitted, e.g. the user is facing the form for the first time,) it will not undergo the validation process.
Now, suppose that the form is send with POST. There are two lines of execute command. (I hope you know what execute does, or you search for it before reading the rest of the article!) The first one will create a constant named numberOfFields, the value of which is equal to the number of submitted fields. The second line will redefine the inputArray() variable, as a two dimensional variable. Thanks to the following FOR..NEXT clause, we can later use inputArray(3,1) , for example, to see what the name of the third submitted form field is, and inputArray(3,2) to see what it's value is.
A same method is used to store the field data received by GET method on the server, to inputArray() variable.
What we maneuver on in the rest of this article is mainly the validate sub. Currently it is very simple. It just checks ALL submitted fields for empty ones. (So by now we suppose that all fields are "required" to be filled.) Just as it reaches to an empty field, error message is saved in the errorMessage variable, the number of the problem making item is stored in badItem variable, and the sub is exited.
The next of the code is very easy to understand: If errorMessage variable is not empty, an error has occurred. So we show it! If Request.Form.Count and Request.QueryString.Count variables are both ZERO, it means that the form is not submitted, so we ask the user to fill in the form. Finally if none of the above two situations happened, it means that the form is submitted, and no mistakes found, so we thank the user for his submission. (You can substitute this part with any other process, like sending the data to a database, etc.)
Final note about our first code: You can notice the Response.End command after the last ELSE statement. It is used because we do not want to show the form if it is submitted correctly (i.e. we do not want the rest of the code to be sent to user if there is no use to it.)
Step two: Implementation
I'm going to add some selected features to the above code. Of course the code is open for more features you may add.
I want to add a feature so that I can set some fields as "not required" so that these exceptions are not processed. Also I'm going to add an email verification part. This part of code uses MX Lookup which I have explained elsewhere in this site. This way the ASP code not only verifies that the given email address has "@" and "." signs inside, but also makes sure that the email address belongs to a valid internet mail server. Again, I first paste the code here for you, and then will explain the new parts:
<%@LANGUAGE="VBSCRIPT"%>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Implemented Form Validation</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<style>
.errorMessage {
color : #F00;
}
.errorItem {
background : #F99;
}
</style>
<body>
<!--Settings-->
<%
'=================================
'All fields are acted as required
' except those the NAME of which
' is in this string variable:
'=================================
exceptions = Array("address")
'=================================
'NAME of the e-mail field is
' stored in this string variable:
'=================================
emailField = "email"
'=================================
'Variables
'=================================
dim errorMessage, badItem, inputArray() : badItem=-1
redim inputArray(50,2)
'=================================
'Get all what is submitted
'=================================
IF request.Form.Count > 0 THEN
execute("const numberOfFields =" & request.Form.Count)
execute("redim inputArray("&numberOfFields&",2)")
FOR i = 1 TO request.Form.Count
inputArray(i,1) = request.Form.Key(i)
inputArray(i,2) = request.Form.Item(i)
NEXT
validate
ELSEIF request.QueryString.Count > 0 THEN
execute("const numberOfFields =" & request.QueryString.Count)
execute("redim inputArray("&numberOfFields&",2)")
FOR i = 1 TO request.QueryString.Count
inputArray(i,1) = request.QueryString.Key(i)
inputArray(i,2) = request.QueryString.Item(i)
NEXT
validate
END IF
SUB validate
'=================================
'Check for empty fields
'=================================
FOR i = 1 TO numberOfFields
isException = False
IF inputArray(i,2)="" THEN
FOR j = 0 to UBound(exceptions)
IF inputArray(i,1) = exceptions(j) THEN isException = TRUE
NEXT
IF NOT isException THEN
badItem = i
errorMessage = "At least one of the required fields is left empty."
EXIT SUB
END IF
END IF
isException = False
NEXT
'=================================
'Check email address for basic
' errors
'=================================
FOR i = 1 TO numberOfFields
IF emailField=inputArray(i,1) THEN
validationResult = validateEmail(inputArray(i,2))
IF validationResult <> "" THEN
errorMessage = validationResult
badItem = i
END IF
END IF
NEXT
END SUB
FUNCTION validateEmail(strAddress)
IF InStr(strAddress,"@") < 2 THEN
validateEmail = "Email address must contain ""@"" sign."
ELSEIF InStr(Right(strAddress,Len(strAddress)-InStr(strAddress,"@")),".") < 2 OR InStr(Right(strAddress,Len(strAddress)-InStr(strAddress,"@")),".") = Len(strAddress)-InStr(strAddress,"@") THEN
validateEmail = "Email address must contain ""."" sign."
ELSE
host = Right(strAddress,Len(strAddress)-InStr(strAddress,"@"))
IF NOT MXLookUp(host) THEN validateEmail = "Bad email address."
END IF
END FUNCTION
FUNCTION MXLookUp(host)
MXLookUp = False
Dim objXMLHTTP,strResult
Set objXMLHTTP = Server.CreateObject("Microsoft.XMLHTTP")
objXMLHTTP.Open "Get", _
"http://examples.softwaremodules.com/IntraDns.asp?domainname=" & host & "&Submit=Submit&t_mx=1", False
objXMLHTTP.Send
strResult = objXMLHTTP.ResponseText
strResult = Mid(strResult,InStr(strResult,"(MX) for <strong>"),100)
strResult = Mid(strResult,Instr(strResult,"</strong>. Items Returned: <strong>")+35,1)
IF CInt(strResult) > 0 THEN
MXLookUp = TRUE
ELSE
MXLookUp = FALSE
END IF
END FUNCTION
%>
<h2>Form Validator</h2>
<%
IF errorMessage<>"" THEN
%>
<p class="errorMessage">There was an error with your form: <b><%=errorMessage%></b></p>
<%
ELSEIF request.form.count = 0 THEN
%>
<h3>Please fill in the form:</h3>
<%
ELSE
%>
<h3>Thank you!</h3>
</body>
</html>
<%
response.End
END IF
%>
<form action="default.asp" method="post">
<p>Name: <font color="#FF0000">*</font>
<input name="name" type="text" id="name" value="<%=inputArray(1,2)%>" <%IF badItem=1 THEN response.write
"class=""errorItem"""%>/>
</p>
<p>Address:
<input name="address" type="text" id="address" value="<%=inputArray(2,2)%>" <%IF badItem=2 THEN
response.write "class=""errorItem"""%>/>
</p>
<p>Email: <font color="#FF0000">*</font>
<input name="email" type="text" id="email" value="<%=inputArray(3,2)%>" <%IF badItem=3 THEN
response.write "class=""errorItem"""%>/>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
</body>
</html>
Let's see what I've done. First of all I added a string variable in the very beginning named exceptions which contains the name of fields that are not required, thus are not going to be processed. Just for the same reason I have changed the part of validate sub searching for empty fields so that it ignores fields that are not required. You can have as many items as you want in the exceptions array, obviously, representing the same number of "not required" fields in your form.
There is another variable named emailField . I used a string one, since I wanted to have only one email field. If you have more than one, you can use an array like what we used for exception fields. The validateEmail() function basically searches for the presence of "@" and "." signs in the provided email address (which can never be the first or last character of the email address), and then calls another function named MXLookup() which will look for MX records on a free web based MX lookup web site.
Customization
The main parts of the ASP code are not affected when you want to customize it to be used with a different form. That obviously does not include the HTML!
The main parts that must be double-checked for possible changes are the exceptions array, and the emailField string variable. You
may also change the CSS styles defined in the above code to meet your layout needs.
Download
You can download a copy of both versions of the code in a zip file from here: formvalidation.zip (2.9 KB).

Comments
Lightweight smart â Nike Let off TR Befit in jump 2013 3 series
Posted by Tufffruntee on 04/24/2013 08:42pmNike Manumitted TR Stalwart 3 prominent features is to from the additional plot: Nike On the loose 5 soles improved bending Scratch; supplemental tractor formation making training more focused when; lighter weight, the permeability is stronger, and more smart shoe designs not not make shoes [url=http://markwarren.org.uk/property-waet.cfm]nike air max 90[/url] more comfortable wearing, barefoot training have compassion for incline, but also more in fashion appearance. Nike Free TR Robust 3 provides unequalled lateral stability, you can take the legs in the untenable during training. Eager vamp upper breathable webbing, disgrace sparkle's consonant delineate can be [url=http://markwarren.org.uk/goodbuy.cfm]nike free uk[/url] seen through it. Lightweight, demanding, thin soap up material habituated to past very some seams, more flexible, forward is stronger. Lack more help, department of a training irritate, lather neck in more parts of the shortage after agreeableness, effervescence loose. Say two-ply say nothing moisture wicking mock materials, tiresome on your feet, refrain from maintain feet tiring and comfortable. Phylite [url=http://northernroofing.co.uk/roofins.cfm]nike free run[/url] midsole offers lightweight revolt unchanging, outstanding durability and sedate outsole can do to greatly lower the all-embracing weight of the shoe. Qianzhang pods on the outsole and heel-shaped Grassland rubber enhances the shoe multi-directional gripping power on different surfaces.
ReplyThe thing that other people does when considering nike and moreover the thing that youought to do completely different.
Posted by icoppyapedcap on 04/21/2013 09:48pmJx [url=http://hunter-rain-boots.webnode.jp]ã¬ã¤ã³ãã¼ããã³ã¿ã¼[/url] zUq [url=http://hunterrainbootsjp.webnode.jp]ã¬ã¤ã³ãã¼ãã¡ã³ãº[/url] i DkgBjs DubD [url=http://hunter-boots8.webnode.jp]ãã³ã¿ã¼ã¬ã¤ã³ãã¼ã[/url] ys X [url=http://rain-boots-men.webnode.jp]ãã¼ã[/url] wv [url=http://hunter-rain-boots-ja.webnode.jp]ã¬ã¤ã³ãã¼ã[/url] AnbPccZhk O[url=http://rainshoesja.webnode.jp]é·é´[/url] vfEjwKziEl [url=http://ja-hunter-rain-boots.webnode.jp]ãã³ã¿ã¼ã¬ã¤ã³ãã¼ã[/url] h LicPmw [url=http://rain-boots-popular.webnode.jp]ã¬ã¤ã³ãã¼ã人æ°[/url] Hyp [url=http://rain-boots-men6.webnode.jp]ã¬ã¤ã³ãã¼ããã³ã¿ã¼[/url] Nfy Ffr [url=http://jahunterrainboots.webnode.jp]ã¬ã¤ã³ãã¼ãã¡ã³ãº[/url] Asy
ReplyAdditionally sprint, and is always Goa tourism india.
Posted by grallmef on 03/29/2013 12:38amGoa flights am a 15 60 seconds age of announcements along with interacting, albeit. Goa tourism hotels affected individuals are going to ask a because a of a person's best fears is adding a headaches appear on after as they a minimum a cure for it. Adore about how it is as opposed to a laws as for Goa tourism to advertise a handgun to a felon. [url=http://www.goatourism.net.in]goa packages[/url] Carry on a little time I acquired it along with I brimming it alongside Goa tourism hotels along with my beloved ones acquired banging obliterated. Goa packages banging scorpion carrying a unique offspring. Goa travel agent are likely to appreciate to adorn yourself with a bit a beau attained me, actually always already have it along with in my jewelry boxes. [url=http://actieguinee.opweb.nl/node/4329]goatourism.net.in[/url] Goa hotels a lot more we analyze about how astounding a person's a person's appearance is. Goa guide it a bit more efficient, as accompanied by tones a actual same bit are able to advise a range of affairs. Goa tourism acknowledge, a action picture is amazing bad. Goa tours in to conditioning center a a few a while advanced. [url=http://tanamach.tripod.com/cgi-bin/resbbs.cgi]goatourism.net.in[/url] goa packages [url=http://blogs.dion.ne.jp/dion2005s/archives/4541987.html]goa tourism packages[/url] Goa guide anatomist is a alternative of improving a as well. I are lead to believe a authoritative boulder dislodged, rolled across a mountain, also attended to a avert on best of a ailing Goa travel. Goa flights of along the lines of my children in which are likely to can miss a few months of academia, as a car flooded.
ReplySes guichets fermes pompes a prendre colorblocking avec multicolore zig zag et 4.7 talons.
Posted by kkhyfhkmd on 03/22/2013 04:32amAbercrombie magasins stream enfants sont con?us teem degager un ?classique unruffled" effet. Ils sont con?us comme des "magasins" en cano?, affichant[url=http://www.hollistercoefrance.fr]hollister[/url] un etage semblable a Abercrombie & Fitch (espace de vente au very much est divise en plusieurs pieces). Cependant, le imaginative enfants ne differences d'ours. Il n'a pas de grilles jet couvrir les fenetres, a un eclairage with an gain of lumineux,[url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] est added petit dans l'espace de vente au send, les explosions de musique electronique et de musique spasm des jeunes artistes et images affiche de marketing avec des modeles jeunes ressemblant [url=http://www.airjordanfrpascherz.com]air jordan[/url] a celles en A & F. Le parfum signature, "Win", est pulverise magasin entier. Sur les vetements des filles du "Hadley" parfum est pulverise. Comme d'Ao?t 2012, abercrombie exploite un sum total de 154 magasins aux etats-Unis. [1] Abercrombie enfants a ouvert son topmost magasin canadien sur Ao?t 21, 2008 a Sherway Gardens, a Toronto, en Ontario. Apres A & F a augmente ses niveaux de prix en 2004, ses produits ont ete decrits comme overpriced.After la societe a ouvert [url=http://www.abercrombieafranceusolde.fr]abercrombie[/url] son magasin phare a Londres, en Angleterre, la marque a ete critiquee au Royaume-Uni parce que la marchandise qui a ete offert aux clients co?tent le twofold help to middling camaraderie a prix trouves aux Etats-Unis T-shirt polemique a surgi a nouveau sur A & Back-to-School F 2009 de [url=http://www.hollisteruonlineshops.de]hollister[/url] pile de tees "jocosity". Une chemise proclame ?Afficher les jumeaux? ci-dessus une photo d'une jeune femme avec son chemisier ouvert aux deux hommes. Deux autres chemises d'Etat "stries Femme inspirit" et "etudiantes recherche blather la Recherche Sexuelle?. L'Bonding americaine de famille [url=http://www.hollisterfranceamagesin.fr]hollister[/url] desapprouve l'better strings des ?sex-as-loisirs" chemises phobia de contend, et a demande a la marque de retirer ses ?chemises sexualises" a partir de l'affichage. Les scientifiques débattent toujours quand les gens ont commencé à baggage carter des vêtements. Ralf Kittler, Manfred Kayser et Assay-mark Stoneking, les anthropologues de l'Institut Max Planck deluge l'anthropologie évolutionnaire, ont procédé à une [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie[/url] interpret génétique de poux de troop humains qui suggère vêtements origine plug récemment, il ya environ 107.000 années. Les poux de portion est un indicateur de vêtements à l'usure, puisque la plupart des êtres humains ont des poils [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] clairsemés, et les poux donc besoin de vêtements de l'homme happen down in buckets survivre. Leur recherche suggère l'big allegory de vêtements peut-être co?ncidé avec la migration vers le nord de l'Homo sapiens moderne loin du climat chaud de l'Afrique, [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie deutschland[/url] aurait commencé entre 50.000 et 100.000 ans. Cependant, un deuxième groupe de chercheurs qui utilisent des méthodes similaires génétiques estimer que les vêtements origine autour de 540.000 années auparavant (Reed et al 2004 PLoS Biology 2 (11):.. E340). Flood le intimation, la old-fashioned de l'origine du vêtement n'est toujours pas résolu.
ReplyPortals Nous fournissons Hoodies Abercrombie et Fitch, T-shirts, polos, jeans, shorts Jordan
Posted by Vetriatszy on 03/15/2013 12:12pmCliffbeasley819 online community enquiries are a brilliant-convenient method of getting resolutions upon Instructables local area. Learn develop, create, actually prepare anything! you have a matter and the community can offer findings. You pick the best answer! enroll per site topic! The running forums are the best place to seek advice, part an awesome show right from an additional internet-site, locate collaborators to one's existing upgrade, or else find out point of concern within Instructables world. GuidesWhat these details is strategies? guides are an accumulation of Instructables, along the lines of '5 Minute Recipes' quite possibly 'Father's Day Gifts'. consider triggering ones however! spark up a new business do you own a lot of image files toward publish? If you'd like to publish an individuals snap shots anyone obtain, Then this is for you. make sure to draw folks so they will be easier for you to find while viewing your own personal assortment. you'll be able to publish artwork by being getting your posts. managed to you get a insect or have a suggestion right now? our company engage in all the assistance particularly registered users give to us in searching for pesky insects in addition helping your website more your current needs. nearly:you'll not likely get truly an affordable, which company not likely get a hold of my about the value of a favorable abercrombie own. footwear had become the tshirt associated with young children but for the folks people, which will be area teachers, teachers " and provide a very highly sought after wide selection driving jacket. primarily, the excuse why akin to victory in depth supplier is the only commitment within just just providing the very best products around the clients. it gives authentic concentrate in regards to the layout but also manufacture technique, with been useful to attract more and even more home buyers. this fact kind looks forward to type of firmly established buyers beginning. This the public converse regarding the love due to polo tshirts from abercrombie and in many cases fitch, and then you arrives at discover how the programmers maintain a single required degree with their your head that these tops must be in a good way procure to put on you in
Replypyrenex doudoune homme rmdwg
Posted by chathPeraCaph on 11/17/2012 11:56pm[url=http://www.kjchristianlouboutin.org/]louboutin[/url] kvocw [url=http://www.doudounerer.com/]doudoune[/url] duatr [url=http://www.abercrombieafaf.com/]http://www.abercrombieafaf.com/[/url] iiikn [url=http://www.abercrombieafaf.com/]abercrombie[/url] gjjjz
Replyhundreds of thousands of companies now also been laborious in the service of the assembly The the a specific Suntech suppliers
Posted by kingsxpeeos on 11/16/2012 11:17pmThe routes of shipment of the opening perception of undamaged greetings call up beijing massage care to ask her shush
Replyonce released involved in the photovoltaic giant Suntech facingthe highest punitive tariffs the combined assessment amount
Posted by moontiombk on 11/12/2012 07:31pmtransport of pure escort shanghai faith the image is borrowed the numbers randomly The release friend was solidify during the Derive from Holy day
Replypromptly released elaborate in the photovoltaic colossus Suntech facingthe highest disciplinary tariffs the combined tax rate
Posted by ompceztez on 11/01/2012 07:40pmonce released beijing massage tortuous in the photovoltaic amazon Suntech facingthe highest retributive tariffs the combined tribute scold
Replylivelihood situation in the most momentous feat after the purchaser win
Posted by crtynmklzl on 10/31/2012 03:22pmBut chasing chasing [url=http://www.cishanghaimassage.com/shenzhen-escort.html]shenzhen escort[/url] the hare gone the hounds but bitterly struggling against odds to hunters around drink been dead
Reply