Form Validation

With ASP, information collected through a form interface is often used to modify a database in some way. Databases are only as good as the data within them. A database saturated with meaningless or improperly formatted data is worthless. Therefore, when creating ASP pages that will directly modify databases based upon input gathered through a form, it is vital that the user entering the form information enters valid data.

The process of ensuring that form fields contain valid input is referred as form validation. Form validation can occur on both the client side and server side. In the next two sections, Section 5.3.1 and Section 5.3.2, we’ll discuss the advantages and disadvantages of each method.

Client-Side Form Validation

Client-side form validation, as the name implies, is form validation that happens on the client. A web page containing a form can optionally contain client-side JavaScript code that will execute when the user attempts to submit the form. This JavaScript code can then scan the user’s form entries, making sure they have a particular format.

The main advantage of client-side form validation is the fact that the validation occurs completely on the client’s computer. Therefore, if the user has entered invalid form data, they don’t have to wait for a round trip to the web server before they know whether or not they’ve entered invalid data. Many sites employ this type of form validation. For example, an e-commerce site might provide form validation for the form fields supplied for the customer’s address.

Client-side form validation is not without its disadvantages, though. If the browser being used does not support JavaScript, or the user has JavaScript disabled, then client-side form validation will not execute. Furthermore, any visitor can easily view the client-side form validation code by viewing the HTML source sent to her browser. If this user wishes to send invalid data, they could take the time to determine what types of data would “slip by” the client-side form validation. Additionally, a visitor entering the URL of the form-processing script into his or her browser and passing illegal form variable values through the querystring can circumvent client-side form validation.

Warning

Also, a malicious user can sidestep client-side form validation through the following sequence of steps:

  1. Save the HTML/client-side validation source code.

  2. Remove the client-side validation source code.

  3. Reload the modified HTML through a browser and submit the form with invalid data.

For this reason, you should not rely on just client-side form validation; it should always be used in conjunction with server-side form validation. Client-side form validation is a nice tool, though, and can be used in addition to server-side form validation.

An example of client-side form validation can be seen in Example 5.2.

Example 5-2. Client-Side Form Validation

<HTML>
<HEAD>
  <SCRIPT LANGUAGE="JavaScript">
  <!--
     function ValidateData(  )
     {
        // Check to make sure the zip code contains either
        // ##### or #####-####
        var strZip = document.frmInfo.Zip.value, iLoop;
        if (strZip.length == 5 || strZip.length == 10)
        {
          // Ok, the zip code is the correct length, make sure
          // it contains all numeric characters if length is
          // 5, or, if length is 10, contains 5 numeric, a dash,
          // and 4 numeric
          if (strZip.length == 5)
          {
             for (iLoop=0; iLoop < strZip.length; iLoop++)
               if (strZip.charAt(iLoop) < '0' ||  strZip.charAt(iLoop) > '9')
               {
                  alert("You have entered an invalid zip code.");
                  return false;
               }
          } else {
             // the string is 10 characters long
             for (iLoop=0; iLoop < 5; iLoop++)
               if (strZip.charAt(iLoop) < '0' ||  strZip.charAt(iLoop) > '9')
               {
                  alert("You have entered an invalid zip code.");
                  return false;
               }

             if (strZip.charAt(5) != '-')
             {
                alert("You have entered an invalid zip code.");
                return false;
             }

             for (iLoop=6; iLoop < strZip.length; iLoop++)
               if (strZip.charAt(iLoop) < '0' ||  strZip.charAt(iLoop) > '9')
               {
                  alert("You have entered an invalid zip code.");
                  return false;
               }
          }
        } else
          {
          alert("The zip code has an invalid number of characters");
          return false;
          }

        // If we've reached this point, the data is valid, so return true
        return true;
     }
  // -->
  </SCRIPT>
</HEAD>
<BODY>
  <FORM NAME=frmInfo METHOD=POST ACTION="somePage.asp"
      ONSUBMIT="return ValidateData(  );">
    Enter your zip code:<BR>
    <INPUT TYPE=TEXT NAME=Zip SIZE=10>
    <P>
    <INPUT TYPE=SUBMIT>
  </FORM>
</BODY>
</HTML>

Tip

Although not demonstrated in Example 5.2, regular expressions are available in JavaScript 1.2, which is available in Netscape and Internet Explorer Version 4.0 and up. Regular expressions, as demonstrated in Example 5.4, make validation much easier.

Server-Side Form Validation

Server-side form validation is form validation that occurs on the web server. Server-side form validation’s major disadvantage is it requires a round trip to the web server to determine whether or not a form field contains valid data. For example, imagine you have a form that asks for the user’s age. Of course, only values between 1 and 120 would be valid entries. An age of -98 is impossible; an age of “Yellow school bus” is nonsensical. If a user enters one of these invalid responses, though, he has to wait for the form field value to be sent to the web server, and have a page returned explaining the data entered was invalid.

Of course, this disadvantage is becoming less and less of an issue as Internet connection speeds become faster and faster. However, with a large number of users still connecting via a modem, this disadvantage is still a legitimate concern. This drawback of server-side validation, though, can be compensated with adequate client-side form validation. When both client-side and server-side form validation are used, the server-side form validation should duplicate the validation performed on the client side. In such a scenario, the server-side form validation serves only as a safety catch in case the user either mistakenly steps around the client-side form validation (perhaps they have JavaScript disabled), or purposely avoids client-side validation (a malicious user).

In Example 5.2, we used client-side form validation to validate a zip code. In Example 5.3, the same data is validated, but this time using server-side validation. It is recommended you use both client-side and server-side form validation when validating user form input.

Example 5-3. Classical Server-Side Form Validation

<% @LANGUAGE="VBSCRIPT" %>
<% Option Explicit %>
<%
   'Read in the form variable
   Dim strZip, iLoop
   strZip = Request("Zip")

   'Check to make sure the zip contains either ##### or #####-####
   If Len(strZip) = 5 or Len(strZip) = 10 then
      ' ok, the zip code is the correct length, make sure
      ' it contains all numeric characters if length is
      ' 5, or, if length is 10, contains 5 numeric, a dash,
      ' and 4 numeric
      If Len(strZip) = 5 then 
        For iLoop = 1 to Len(strZip)
          If Asc(Mid(strZip, iLoop, 1)) < Asc("0") or _
              Asc(Mid(strZip, iLoop, 1)) > Asc("9") then
            Response.Write "You entered an invalid zip code."
            Response.End
          End If
        Next
      Else
        ' the string is 10 characters long
        For iLoop=1 to 5
          If Asc(Mid(strZip, iLoop, 1)) < Asc("0") or _
              Asc(Mid(strZip, iLoop, 1)) > Asc("9") then
            Response.Write "You entered an invalid zip code."
            Response.End
          End If
        Next

        If Asc(Mid(strZip, iLoop, 6)) <> Asc("-") then
          Response.Write "You entered an invalid zip code."
          Response.End
        End If

        For iLoop=7 to Len(strZip)
          If Asc(Mid(strZip, iLoop, 1)) < Asc("0") or _
              Asc(Mid(strZip, iLoop, 1)) > Asc("9") then
            Response.Write "You entered an invalid zip code."
            Response.End
          End If
        Next
       End If
   Else
      Response.Write "You entered an invalid zip code."
      Response.End
   End If

   ' If we reached here, we had valid input, continue
   ' with form processing...
   Response.Write "You entered valid input, thanks!"
%>

In Example 5.3, classical VBScript methods were used to validate a particular input. While these methods are sufficient, they leave a lot to be desired. With the VBScript 5.0 scripting engine, a new regular expression object has been added, allowing regular expression pattern matching in VBScript!

Regular expressions offer more robust form-validation techniques than simply using the techniques in Example 5.3. Example 5.4 uses regular expression matching to perform the same form validation as in Example 5.3.

Example 5-4. Server-Side Form Validation via Regular Expressions

<% @LANGUAGE="VBSCRIPT" %>
<% Option Explicit %>
<%
   'Read in the form variable
   Dim strZip, iLoop
   strZip = Request("Zip")

   'Check to make sure the zip contains either ##### or #####-####
   Dim objRegExp
   Set objRegExp = New regexp

   objRegExp.Pattern = "^d{5}(-d{4})?$"

   If Not objRegExp.Test(strZip) then
     Response.Write "Invalid input - zip code has an invalid value!"
     Response.End
   End If

   'Otherwise, we have valid, so do stuff!
   ' ...
   Response.Write "Valid data!!!"
%>

For more information on form validation, be sure to check out the following on-line resources:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.13.173