adOpenStatic Logo
Navigation
Home
FAQ
Ken's Blog
Resources
Contact Ken
Copyright 2000 -



Server-Side Validation

<%
If isPostBack() then

   ' Perform server-side validation here

   ' If no errors after validation then

      ' Do database/etc work
      ' Redirect to next page

   ' Else load form values

Else

   ' Load default/initial form values

End If
%>

<!-- Load default page header/body/navigation etc -->
<!-- Load error messages -->
<!-- Load javascript validators -->
<!-- Load HTML form -->
<!-- Load default page footer etc -->

 

 

 

Looking at this part.


We now begin to look at how we are going to handle the user input once it has arrived at the server. Again we need to rigorously test the user input and ensure that only that data that passes our tests is able to then be entered in our database (or emailed or whatever).

The way that I deal with server-side validation follows the following process:

  • Create a master list of possible errors, and associated error messages. We use a Scripting.Dictionary object to hold the error key and associated message
  • Create a variable to hold the errors that are actually encountered
  • Test each piece of user input, and if it fails the test we add the appropriate error key to the variable that is holding our errors
  • At the beginning of the next stage (ie doing our database work) examine the error variable. If it is Empty then no errors have been encountered, and we proceed. If however, the error variable is no longer empty then we have encountered one or more errors, and we skip the data processing section. Instead we reload the form, and we call a routine that will write out the corresponding error messages (from our master list in our Dictionary object) to the screen.

Recall the form from the previous page - it had three text boxes. Our validation rules where that the first text box required some input, the second required at least 5 characters, and the third allowed only digits. I'm going to add another rule. If the input from either input box 1 or 2 is longer than 50 characters then we're going to truncate the input at 50 (so as not to generate an error when we insert too long a string into our database). However if the input from input box 3 is longer than 10 characters, we're going to generate an error. Remember though, that there is no requirement to enter something into text box 3, only that whatever is entered is numbers only, and no greater than 10 digits.

Our code starts to look like this:

<%
Dim errCode
Dim objErrors

If isPostBack() then

   '----------------------------------------
   ' --- Save our form input to local variables
   '----------------------------------------
   strTxt1 = Request.Form("txt1")
   strTxt2 = Request.Form("txt2")
   strTxt3 = Request.Form("txt3")

   '----------------------------------------
   ' --- Create our master list of errors
   '----------------------------------------
   Set objErrors = Server.CreateObject("Scripting.Dictionary")
   objErrors.Add "strTxt1-Missing", "You did not enter a value in the 1st field"
   objErrors.Add "strTxt2-TooShort", "Please enter at least 5 characters in the 2nd field"
   objErrors.Add "strTxt3-TooLong", "Please enter no more than 10 characters in the 3rd field"
   objErrors.Add "strTxt3-Invalid", "Please enter only digits (0-9) in the 3rd field"

   '----------------------------------------
   ' --- Begin UI Validation
   '----------------------------------------
   If not TestMinLength(strTxt1, 1) then errCode = AddUserError(errCode, "strTxt1-Missing")
   If not TestMaxLength(strTxt1, 50) then strTxt1 = Left(strTxt1, 50)

   If not TestMinLength(strTxt2, 5) then errCode = AddUserError(errCode, "strTxt2-TooShort")
   If not TestMaxLength(strTxt2, 50) then strTxt2 = Left(strTxt2, 50)

   If not TestMaxLength(strTxt3, 10) then errCode = AddUserError(errCode, "strTxt3-TooLong")
   If not IsAcceptableValues(strTxt3, "0123456789", 0, 0) then _
      errCode = AddUserError(errCode, "strTxt3-Invalid")

   If isEmpty(errCode) then

      ' No errors, so proceed

   Else

      ' Some errors so reload form

   End If
%>

A couple of quick points before we look at some of the validation functions. Firstly we can see that we allocated the values in the Request.Form() collection to local variables. These are the same variables we used to populate the original HTML form. When the form reloads, whatever the user input (plus any modifications we might make) are reloaded back into the form. For example, with strTxt1, we could truncate it to 50 characters, generate an error, and then reload the truncated string automatically into the form, by modifying the line:

   If not TestMaxLength(strTxt1, 50) then strTxt1 = Left(strTxt1, 50)

to read like this instead:

   If not TestMaxLength(strTxt1, 50) then
      errCode = AddUserError(errCode, "strTxt1-TooLong")
      strTxt1 = Left(strTxt1, 50)
   End If

Adding "strTxt1-TooLong" to the errorcode stops the database work happening. At the same time strTxt1 is still truncated to just 50 characters.

The second thing to be aware of is that AddUserError() merely adds the supplied error code to the errCode variable, separating each error with a comma. Later on we use the VBScript Split() function to generate an array, and use those values as keys to extract the associated value from the Dictionary object. The code for AddUserError() is as follows:

<%
Function AddUserError( _
   ByVal errCode, _
   ByVal errCodeToAdd _
   )

   If isEmpty(errCode) then
      AddUserError = errCodeToAdd
   Else
      AddUserError = errCode & "," & errCodeToAdd
   End If

End Function
%>

Now we look at some of the validation functions. I've chosen to highlight 2. The first is a simple function that merely tests for a minimum length - TestMinLength(). The second is more complex, and tests to see if a string contains acceptable values only.

<%
'----------------------------------------
' Accepts strInput as the string to test for minimum length
' Accepts intMinLength as integer - minimum length strInput has to be
' Returns True or False
'----------------------------------------


Function TestMinLength( _
   ByVal strInput, _
   ByVal intMinLength _
   )

   If Len(strInput & "") >= intMinLength then
      TestMinLength = True
   Else
      TestMinLength = False
   End If

End Function
%>

The second function is more complex:

<%
'----------------------------------------
' Checks to see if the input string contains only chars in the acceptable
' values list that is also passed in. If no acceptable chars parameter is
' passed in, then a default list is used (saves on repeatedly passing in
' chars like A-Z, 1-9 etc)
' Optionally the passed in acceptable chars parameter can be appended
' to the default list.
' Accepts strInput as string - string to be tested
' Accepts strAcceptChars as string - string of acceptable values
' Accepts blnAppend as 0/1 - If 1 then append strAcceptChars to default list
' otherwise substitute strAcceptChars for the default list
' Accepts intCompareTypeEnum as 0/1. If 1 then compare type is vbTextCompare
' otherwise compare type is vbBinaryCompare
' Returns True or False
' © Ken Schaefer (adOpenStatic.com) 2001
'----------------------------------------


Function IsAcceptableValues( _
   ByVal strInput, _
   ByVal strAcceptChars, _
   ByVal blnAppend, _
   ByVal intCompareTypeEnum _
   )

   On Error Resume Next
   Const
Proc = "IsAcceptableValues"

   Dim strToCheck ' String we are checking
   Dim strDefaultList ' Default list of acceptable chars
   Dim strMasterList ' Master list of acceptable chars
   Dim intComp ' Compare Type
   Dim i ' Loop Counter

   ' Set Default Values
   strToCheck = Trim(strInput)
   IsAcceptableValues = True
   ' Edit this next list to be your set of default values
   strDefaultList = _
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
      "abcdefghijklmnopqrstuvwxyz" & _
      "1234567890"

   ' Set up the master list of acceptable chars
   If strAcceptChars & "" = "" then

      ' We have no passed in acceptable chars
      ' so set master list to the default list

      strMasterList = strDefaultList

   Else

      If blnAppend = 1 then

         ' We have a list of available chars, and we need to append
         ' it to the default list to create the master list

         strMasterList = strDefaultList & strAcceptChars

      Else

         ' We have a list of available chars but we don't want to append it to
         ' the default list, so set master list equal to input acceptable chars

         strMasterList = strAcceptChars

      End if

   End if

   ' Make sure we have a valid CompareTypeEnum
   ' 0 = vbBinaryCompare (Case Sensitive)
   ' 1 = vbTextCompare (Case Insensitive)
   ' If we have none, set to 0

   If CStr(intCompareTypeEnum) <> CStr("1") then
      intComp = 0
   Else
      intComp = 1
   End if

   ' Begin validation
   For i = 1 to Len(strToCheck)
      If inStr(1, strMasterList, Mid(strToCheck, i, 1), intComp) = 0 then

         IsAcceptableValues = False
         Exit For

      End if
   Next

   If Err.number <> 0 then
      Call subWriteError(Err.number, Proc, Err.Description)
   End if

End Function ' IsAcceptableValues
%>

The above two functions are only a fraction of what you'll end up needing. I suggest you also develop functions to test for maximum length, for numbers, dates, minimum and maximum values. You may also want to develop functions that test to see if input is in a certain format that may be specified to your application (eg tax file numbers (Australia), credit card numbers, and if you're in the US - SSNs).

Back to Client Side validation | Onto generating the errors

Back to Code Listing