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

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read