Share via


Processing User Input

By using the ASP Request Object object, you can create simple, yet powerful scripts for collecting and processing data gathered with HTML forms. In this topic, you will not only learn how to create basic form processing scripts, but also acquire useful techniques for validating form information, both on your Web server and at the user's browser.

About HTML Forms

HTML forms, the most common method for gathering Web-based information, consist of arrangements of special HTML tags that render user interface elements on a Web page. Text boxes, buttons, and check boxes are examples of elements that enable users to interact with a Web page and submit information to a Web server.

For example, the following HTML tags generate a form where a user can enter their first name, last name, and age, and includes a button for submitting information to a Web server. The form also contains an hidden input tag (not displayed by the Web browser) that you can use to pass additional information to a Web server.

  <FORM METHOD="Get" ACTION="Profile.asp">
<INPUT TYPE="Text" NAME="FirstName"> 
<INPUT TYPE="Text" NAME="LastName">
<INPUT TYPE="Text" NAME="Age">
<INPUT TYPE="Hidden" NAME="UserStatus" VALUE="New">
<INPUT TYPE="Submit" VALUE="Enter">
</FORM>

Detailing the complete set of HTML form tags is outside the scope of this topic, however, there are numerous sources of information that you can use to learn about creating useful and engaging HTML forms. For example, use your Web browser's source viewing feature to examine how HTML forms are created on other Web sites. Also, visit the Microsoft MSDN Online Web site to learn innovative ways of using HTML forms with other Internet technologies.

Processing Form Inputs with ASP

After creating an HTML form, you will need to process user input, which means sending the information to an .asp file for parsing and manipulation. Once again, examine the HTML code from the previous example. Notice that the <FORM> tag's ACTION attribute refers to a file called Profile.asp. When the user submits HTML information, the browser uses the POST method to send to the information to an .asp file on the server, in this case Profile.asp. The .asp file may contain scripts that process information and interact with other scripts, COM components, or resources, such as a database.

Using ASP, there are three basic ways to collect information from HTML forms:

  • A static .htm file can contain a form that posts its values to an .asp file.
  • An .asp file can create a form that posts information to another .asp file.
  • An .asp file can create a form that posts information to itself, that is, to the .asp file that contains the form.

The first two methods operate in the same way as forms that interact with other Web server programs, except that with ASP, the task of collecting and processing form information is greatly simplified. The third method is a particularly useful and will be demonstrated in the Validating Form Input section.

Getting Form Input

The ASP Request object provides two collections that facilitate the task of retrieving form information sent with as a URL request.

The QueryString Collection

The Request.QueryString Collection collection retrieves form values passed to your Web server as text following a question mark in the request URL. The form values can be appended to the request URL by using either the HTTP GET method or by manually adding the form values to the URL.

For example, if the previous form example used the GET method (METHOD="GET") and the user typed Clair, Hector, and 30, then the following URL request would be sent to the server:

https://Reskit/Workshop1/Painting/Profile.asp?FirstName=Clair&LastName=Hector&Age=30&UserStatus=New

Profile.asp might contain the following form processing script:

  Hello <%= Request.QueryString("FirstName") %> <%= Request.QueryString("LastName") %>. 
You are <%= Request.QueryString("Age") %> years old!

<%
  If Request.QueryString("UserStatus") = "New" Then 
    Response.Write "This is your first visit to this Web site!"
  End if    
%>

In this case, the Web server would return the following text to the user's Web browser:

Hello Clair Hector. You are 30 years old! This is your first visit to this Web site!

The QueryString collection also has an optional parameter that you can use to access one of multiple values that appear in the URL request (using the GET method). You can also use the Count property to count the number of times that a specific type of value appears.

For example, a form containing a list box with multiple items can generate the following request:

https://Reskit/OrganicFoods/list.asp?Food=Apples&Food=Olives&Food=Bread

You could use the following command to count multiple values:

Request.QueryString("Food").Count

To display the multiple values types, List.asp could contain the following script:

  <%
  lngTotal = Request.QueryString("Food").Count
  For i = 1 To lngTotal
    Response.Write Request.QueryString("Food")(i) & "<BR>"
  Next
%>

The preceding script would display: FakePre-bc95ceb7a290498e955760e486e69959-194b84021c36417a931f4ab332abb866

You can also display the entire list of values as a comma-delimited string by using the following:

  <% Response.Write Request.QueryString("Item") %>

This would display the following string:

Apples, Olives, Bread

Form Collection

When you use the HTTP GET method to pass long and complex form values to a Web server, you run the risk of losing information. Some Web servers tend to restrict the size of the URL query string, so that lengthy form values passed with the GET method might be truncated. If you need to send a large amount of information from a form to a Web server, you should use the HTTP POST method. The POST method, which sends form data in the HTTP request body, can send a an almost unlimited number of characters to a server. You can use the ASP Request object's Request.Form Collection collection to retrieve the values sent with the POST method.

The Form collection stores values in a manner similar to the QueryString collection. For example, if a user filled out a form by entering a long list of names, then you could retrieve the food names with the following script:

  <%
  lngTotal = Request.Form("Food").Count
  For i = 1 To lngTotal 
   Response.Write Request.Form("Food")(i) & "<BR>"
  Next
%>

Validating Form Input

A well-designed Web form often includes a client script that validates user input prior to sending information to the server. Validation scripts can check for such things as whether the user entered a valid number or whether a text box was left empty. Imagine that your Web site includes a form that enables users to compute the rate of return on an investment. You will probably want to verify whether a user has actually entered numerical or text information in the appropriate form fields, prior to sending potentially invalid information to your server.

In general, it's good practice to do as much form validation as possible on the client side. Beyond prompting users more quickly about input errors, client-side validation yields faster response times, reduces server loads, and frees bandwidth for other applications.

The following client-side script validates user-input (in this case, the script determines whether an account number entered by the user is actually a number) prior to sending information to the server:

  <SCRIPT LANGUAGE="JScript">
    
function CheckNumber()
{           
 if (isNumeric(document.UserForm.AcctNo.value))
   return true
 else
 {
   alert("Please enter a valid account number.")
   return false
 }      
}
    
//Function for determining if form value is a number.
//Note:  The JScript isNaN method is a more elegant way to determine whether
//a value is not a number. However, some older browsers do not support this method.
function isNumeric(str)
{
  for (var i=0; i < str.length; i++)
        {
    var ch = str.substring(i, i+1)
    if( ch < "0" || ch>"9" || str.length == null)
                {
      return false
    }
  }
  return true
}   
</SCRIPT>

<FORM METHOD="Get" ACTION="balance.asp" NAME="UserForm" ONSUBMIT="return CheckNumber()">

    <INPUT TYPE="Text"   NAME="AcctNo">
    <INPUT TYPE="Submit" VALUE="Submit">
    
</FORM>

If form validation requires database access, however, you should consider using server-side form validation. A particularly advantageous way of carrying out server-side validation is to create a form that posts information to itself. That is, the .asp file actually contains the HTML form that retrieves user input. (Remember, you can use ASP to interact with client-side scripts and HTML. For more information, see Interacting with Client-Side Scripts.) The input is returned to the same file, which then validates the information and alerts the user in case of an invalid input.

Using this method of processing and validating user input can greatly enhance the usability and responsiveness of your Web based forms. For example, by placing error information adjacent to the form field where invalid information was entered, you make it easier for the user to discover the source of the error. (Typically, Web-based forms forward requests to a separate Web page containing error information. Users who do not immediately understand this information may become frustrated.)

For example, the following script determines whether a user entered a valid account number by posting information to itself (Verify.asp) and calling a user defined function that queries a database:

  <% 
  strAcct = Request.Form("Account")
  If Not AccountValid(strAcct) Then   
    ErrMsg = "<FONT COLOR=Red>Sorry, you may have entered an invalid account number.</FONT>"
  Else
    Process the user input
    .
    .
    .   
    Server.Transfer("Complete.asp")
  End If

  Function AccountValid(strAcct)
    A database connectivity script or component method call goes here.
  End Function 
%>

<FORM METHOD="Post"  ACTION="Verify.asp">   
Account Number:  <INPUT TYPE="Text" NAME="Account"> <%= ErrMsg %> <BR> 
<INPUT TYPE="Submit">         
</FORM>

In this example, the script is located in a file named Verify.asp, the same file that contains the HTML form; it posts information to itself by specifying Verify.asp in the ACTION attribute.

important Important If your are using JScript for server-side validation, be sure to place a pair of empty parentheses following the Request collection item (either QueryString or Form) when you are assigning the collection to a local variable. Without parenthesis, the collection returns an object, rather than a string. The following script illustrates the correct way to assign variables with JScript:

  <%
   var Name = Request.Form("Name")();
   var Password = Request.Form("Password")();

  if(Name > "")
  {
     if(Name == Password)
      Response.Write("Your name and password are the same.")
  else
      Response.Write("Your name and password are different.");
  }
%>

VBScript exhibits the same behavior if the collection contains multiple values that are comma-separated or indexable. This means that for both VBScript and JScript, in addition to placing a pair of empty parentheses following the Request collection item, you will need to specify the index of the desired value. For example, the following line of JScript returns only the first of multiple values for a form element:

  var Name = Request.Form("Name")(1);