ASP Classic Built-In Ajax CAPTCHA Validation VBScript Code Sample (BotDetect v3.0; deprecated)

The ASP Classic built-in Ajax Captcha validation code sample shows how to properly perform Ajax CAPTCHA validation using built-in BotDetect Classic ASP Captcha client-side functionality, which doesn't require any 3rd party Ajax frameworks.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

It uses the Captcha Form Sample as a starting point, and adds client-side validation of all form fields.

Ajax CAPTCHA validation improves the user experience by reducing CAPTCHA validation response time, giving users much faster feedback about the validation result.

Client-side validation is not secure by itself (it can be bypassed trivially), so the sample also shows how the protected form action must always be secured by server-side CAPTCHA validation as well.

In case of any Ajax errors or timeouts, the sample simply falls back to full form posting and server-side CAPTCHA validation.

Installed Location

By default, the Classic ASP built-in Ajax Captcha validation code sample is installed at:
C:\Program Files\Lanapsoft\BotDetect 3 CAPTCHA Component\Asp\WebApp\CaptchaAjaxValidationSample

You can also run it from the BotDetect Start Menu:
Programs > Lanapsoft > BotDetect 3 CAPTCHA Component > ASP > Web Applications > Run

Default.asp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>BotDetect ASP CAPTCHA Ajax Validation Sample</title>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <!-- #include file ="BotDetect.asp" -->
</head>
<body>
  <form method="post" action="ProcessForm.asp" id="form1">

    <h1>BotDetect ASP CAPTCHA Ajax Validation Sample</h1>
    
    <h2>Add Message</h2>
    
    <fieldset>
      <legend>CAPTCHA included in ASP form Ajax validation</legend>
      
      <div class="input">
        <label for="Name">Name:</label>
        <input type="text" name="Name" id="Name" class="textbox" 
        value="<%=Request("Name") %>" />
        <span class="incorrect" id="NameValidator" style="display:<% 
        If Request("nameValid") = "False" Then %>inline<% Else %>none<
        % End If %>;">*</span>
      </div>
      
      <div class="input">
        <label for="Email">Email:</label>
        <input type="text" name="Email" id="Email" class="textbox" 
        value="<%=Request("Email") %>" />
        <span class="incorrect" id="EmailValidator" style="display:<% 
        If Request("emailValid") = "False" Then %>inline<% Else %>none<
        % End If %>;">*</span>
      </div>
      
      <div class="input">
        <label for="Message">Short message:</label>
        <textarea class="inputbox" id="Message" name="Message" 
        rows="5" cols="40"><%=Request("Message") %></textarea>
        <span class="incorrect" id="MessageValidator" style="display:<
        % If Request("messageValid") = "False" Then %>inline<% Else %>
        none<% End If %>;">*</span>
      </div>
        
      <div class="input">
        <% ' Adding BotDetect CAPTCHA to the page 
          Dim FormCaptcha : Set FormCaptcha = (New Captcha)("FormCaptcha")
          FormCaptcha.UserInputID = "CaptchaCode"
          
          If Not FormCaptcha.IsSolved Then %>
            <label for="CaptchaCode">Retype the characters from the 
            picture:</label>
            <%=FormCaptcha.Html %>
            <input type="text" name="CaptchaCode" id="CaptchaCode" 
            class="textbox" />
            <span class="incorrect" id="CaptchaValidator" 
            style="display:<% If Request("captchaValid") = "False" 
            Then %>inline<% Else %>none<% End If %>;">*</span><%
          End If
        %>
        
      </div>
      <input type="submit" name="SubmitButton" id="SubmitButton" 
      value="Submit" onclick="return validateForm();" />
    </fieldset>
    
    <br />
    
    <p class="navigation"><a href="Messages.asp">View Messages</a></p>
    
  </form>
  
  <script type="text/javascript" src="Validation.js"></script>
  
  <script type="text/javascript">
    BotDetect.RegisterCustomHandler('PreAjaxValidate', OnCaptchaValidate);
    BotDetect.RegisterCustomHandler('AjaxValidationFailed', OnCaptchaIncorrect);
    BotDetect.RegisterCustomHandler('AjaxValidationPassed', OnCaptchaCorrect);
    BotDetect.RegisterCustomHandler('AjaxValidationError', OnAjaxError);
    
    function validateCaptcha() {
      var result = false;
      
      var input = document.getElementById("CaptchaCode");
      if (input && 'text' == input.type) {
        var value = input.value.replace(/^\s+|\s+$/g,""); // trim 
        leading and trailing whitespace
        if (value && value.length > 0 && value.length < 10) {
          result = <%=FormCaptcha.CaptchaID %>.Validate();
        }
      }
      
      var validator = document.getElementById("CaptchaValidator");
      updateValidatorDisplay(validator, result);
      
      return result;
    }
  </script>
  
</body>
</html>

The Captcha Ajax validation workflow is controlled by four client-side events: OnCaptchaValidation, OnCaptchaCorrect, OnCaptchaIncorrect and OnAjaxError. We register custom handlers (defined in the Validation.js file, see below) which control how the form behaves in various stages.

The validateCaptcha() function performs simple pre-processing of the user input (trimming and checking it's not empty) before calling the Validate() function exposed by the BotDetect client-side object interface. It is placed here instead of the external JavaScript file so it can simply evaluate the <%=FormCaptcha.CaptchaID %> ASP expression to get the client-side BotDetect object instance.

Validation.js

function validateForm() {
  var isNameValid = validateName();
  var isEmailValid = validateEmail();
  var isMessageValid = validateMessage();
  var isCaptchaValid = validateCaptcha();
  
  return isNameValid && isEmailValid && isMessageValid && 
  isCaptchaValid;
}

function validateName() {
  var result = false;
  
  var input = document.getElementById("Name");
  if (input && 'text' == input.type) {
    var value = input.value.replace(/^\s+|\s+$/g,""); // trim leading 
    and trailing whitespace
    if (value && value.length > 2 && value.length < 30) {
      result = true;
    }
  }
  
  var validator = document.getElementById("NameValidator");
  updateValidatorDisplay(validator, result);
  
  return result;
}

function validateEmail() {
  var result = false;
  
  var input = document.getElementById("Email");
  if (input && 'text' == input.type) {
    var value = input.value.replace(/^\s+|\s+$/g,""); // trim leading 
    and trailing whitespace
    if (value && value.length > 5 && value.length < 100 && value.match(
    /^(.+)@(.+)\.(.+)$/)) {
      result = true;
    }
  }
  
  var validator = document.getElementById("EmailValidator");
  updateValidatorDisplay(validator, result);
  
  return result;
}

function validateMessage() {
  var result = false;
  
  var input = document.getElementById("Message");
  if (input && 'textarea' == input.type) {
    var value = input.value.replace(/^\s+|\s+$/g,""); // trim leading 
    and trailing whitespace
    if (value && value.length > 2 && value.length < 255) {
      result = true;
    }
  }
  
  var validator = document.getElementById("MessageValidator");
  updateValidatorDisplay(validator, result);
  
  return result;
}


function OnCaptchaValidate() {
  // hide validator
  var captchaValidator = document.getElementById("CaptchaValidator");
  updateValidatorDisplay(captchaValidator, true);
  
  // disable multiple clicks while waiting for server response
  var submitButton = document.getElementById("SubmitButton");
  submitButton.disabled = true;
  submitButton.value = 'Validating...';
}

function OnCaptchaCorrect() {
  // hide validator
  var captchaValidator = document.getElementById("CaptchaValidator");
  updateValidatorDisplay(captchaValidator, true);
  
  // automatically proceed to server-side validation
  var submitButton = document.getElementById("SubmitButton");
  submitButton.disabled = false;
  submitButton.value = 'Submit';
  submitButton.focus();
  submitButton.click();
}

function OnCaptchaIncorrect() {
  // show validator
  var captchaValidator = document.getElementById("CaptchaValidator");
  updateValidatorDisplay(captchaValidator, false);
  
  // allow the users to re-try the new Captcha 
  var submitButton = document.getElementById("SubmitButton");
  submitButton.disabled = false;
  submitButton.value = 'Submit';
}
      
function OnAjaxError() {
  // fall back to server-side validation
  var submitButton = document.getElementById("SubmitButton");
  submitButton.disabled = false;
  submitButton.value = 'Submit';
  submitButton.focus();
  submitButton.click();
}

function updateValidatorDisplay(validator, result) {
  if (validator) {
    if (result) { 
      validator.style.display = 'none'; 
    } else {
      validator.style.display = 'inline'; 
    }
  }
}

The first part of the script defines validation methods for other form fields and is not relevant for Ajax Captcha validation implementation.

Handlers for the four Ajax-related client-side events will be automatically called by the Validate() function call at appropriate stages of the Ajax Captcha validation workflow.

Main concerns of these handlers are displaying the validation result, disabling multiple consecutive button clicks while Ajax validation is in progress, and handling Ajax errors and timeouts.

Details of the Ajax implementation are encapsulated in BotDetect source for easier use. They involve making an Ajax request at a special endpoint in the Captcha handler, and processing the returned JSON result. You do not need to concern yourself with such details, but can use the supplied Validate() function as is.

ProcessForm.asp

<!-- #include file ="BotDetect.asp" -->
<% 
  Dim form_page : form_page = "Default.asp"
  Dim view_page : view_page = "Messages.asp"
  
  'directly accessing this script is an error
  If Not Request.ServerVariables("REQUEST_METHOD") = "POST" Then
    Response.Redirect form_page
  End If

  ' submitted data
  Dim name : name = Request("name")
  Dim email : email = Request("email")
  Dim message : message = Request("message")
  form_page = form_page & "?name=" & Server.URLEncode(name) & 
  "&email=" & Server.URLEncode(email) & "&message=" & Server.URLEncode(
  message)

  ' total form validation result
  Dim isPageValid : isPageValid = True
  
  ' Captcha validation 
  Dim FormCaptcha : Set FormCaptcha = (New Captcha)("FormCaptcha")
  FormCaptcha.UserInputID = "CaptchaCode"
  If Not FormCaptcha.IsSolved Then
    Dim isHuman : isHuman = FormCaptcha.Validate()
    isPageValid = isPageValid And isHuman
    form_page = form_page & "&captchaValid=" & isHuman
  End If
  
  ' name validation
  Dim isNameValid : isNameValid = ValidateName(name)
  isPageValid = isPageValid And isNameValid
  form_page = form_page & "&nameValid=" & isNameValid
  
  ' email validation
  Dim isEmailValid : isEmailValid = ValidateEmail(email)
  isPageValid = isPageValid And isEmailValid
  form_page = form_page & "&emailValid=" & isEmailValid
  
  ' message validation
  Dim isMessageValid : isMessageValid = ValidateMessage(Message)
  isPageValid = isPageValid And isMessageValid
  form_page = form_page & "&messageValid=" & isMessageValid
  
  If Not isPageValid Then 
    ' form validation failed, show error message
    Response.Redirect form_page
  End If
  
  ' keep a collection of submitted valid messages in Application state
  Call SaveMessage(name, message)
  Call FormCaptcha.Reset
  Response.Redirect view_page
  
  ' name validation
  Function ValidateName(name)
    Dim result : result = False
    If (Len(name) > 2 And Len(name) < 30) Then
      result = True
    End If
    ValidateName = result
  End Function
  
  ' email validaton
  Function ValidateEmail(email)
    Dim result : result = False
    If (Len(email) < 5 Or Len(email) > 100) Then
      result = False
    Else
      Dim regEx : Set regEx = New RegExp
      regEx.Pattern = "^(.+)@(.+)\.(.+)$"
      result = regEx.Test(email)
    End If
    ValidateEmail = result
  End Function
  
  ' message
  Function ValidateMessage(message)
    Dim result : result = False
    If (Len(message) > 2 And Len(message) < 255) Then
      result = True
    End If
    ValidateMessage = result
  End Function
  
  ' data storage
  Sub SaveMessage(name, email, message)
    ' we want to keep the sample code simple, so we'll store the 
    messages in Application state despite it being unfit for real-
    world use in such scenarios;
    ' using a database or another appropriate persistence medium would 
    complicate the sample code
    Application.Lock
    Application("Message_" & FormCaptcha.InstanceID) = Server.
    HTMLEncode(name) & " (" & Server.HTMLEncode(email) & ") says: " & 
    Server.HTMLEncode(message)
    Application.UnLock
  End Sub
  
%>

Server-side Captcha validation is a necessary fallback for all Ajax uses, as explained in the Captcha Validation & Security FAQ.

Messages.asp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>BotDetect ASP CAPTCHA Ajax Validation Sample</title>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

  <h1>BotDetect ASP CAPTCHA Ajax Validation Sample</h1>
  
  <h2>View Messages</h2>

  <%
   Dim count : count = 0
    For Each val In Application.Contents
      If InStr(val, "Message_") And Application(val) <> "" Then
        Response.Write "<p class=""message"">" & Application(val) & "<
        /p>"
        count = count + 1
      End If
    Next
    
    If count = 0 Then
      Response.Write "<p class=""message"">No messages yet.</p>"
    End If
  %>
  
  <br />
  
  <p class="navigation"><a href="Default.asp">Add Message</a></p>
    
</body>
</html>

BotDetect\CaptchaConfig.asp

<%

' Captcha code configuration
' ---------------------------------------------------------------------
LBD_Configuration_CodeLength = 3
LBD_Configuration_CodeStyle = LBD_CodeStyles("Alphanumeric")
LBD_Configuration_CodeTimeout = 1200
LBD_Configuration_Locale = "en-US"
LBD_Configuration_CustomCharset = ""
LBD_Configuration_BannedSequences = ""

' Captcha image configuration
' ---------------------------------------------------------------------
LBD_Configuration_ImageStyle = LBD_ImageStyles("Graffiti2")
LBD_Configuration_ImageWidth = 150
LBD_Configuration_ImageHeight = 50
LBD_Configuration_ImageFormat = LBD_ImageFormats("JPEG")
LBD_Configuration_CustomDarkColor = ""
LBD_Configuration_CustomLightColor = ""
LBD_Configuration_ImageTooltip = "CAPTCHA"
LBD_Configuration_HelpLinkEnabled = True
LBD_Configuration_HelpLinkMode = LBD_HelpLinkModes("Image")
LBD_Configuration_HelpLinkUrl = ""
LBD_Configuration_HelpLinkText = ""

' Captcha sound configuration
' ---------------------------------------------------------------------
LBD_Configuration_SoundEnabled = True
LBD_Configuration_SoundStyle = LBD_RandomSoundStyle()
LBD_Configuration_SoundFormat = LBD_SoundFormats("WavPcm16bit8kHzMono")
LBD_Configuration_SoundTooltip = "Speak the CAPTCHA code"
LBD_Configuration_SoundIconUrl = "BotDetect/SoundIcon.gif"
LBD_Configuration_SoundPackageFolder = "C:\Program Files (x86)
\Lanapsoft\BotDetect 3 CAPTCHA 
Component\Asp\Redistribute\BotDetectSounds"
LBD_Configuration_WarnAboutMissingSoundPackages = True
LBD_Configuration_SoundStartDelay = 0
LBD_Configuration_SoundRegenerationMode = LBD_SoundRegenerationModes("Limited")

' Captcha reload configuration
' ---------------------------------------------------------------------
LBD_Configuration_ReloadEnabled = True
LBD_Configuration_ReloadTooltip = "Change the CAPTCHA code"
LBD_Configuration_ReloadIconUrl = "BotDetect/ReloadIcon.gif"
LBD_Configuration_AutoReloadExpiredCaptchas = True
LBD_Configuration_AutoReloadTimeout = 7200

' Captcha user input  configuration
' ---------------------------------------------------------------------
LBD_Configuration_AutoFocusInput = True
LBD_Configuration_AutoClearInput = True
LBD_Configuration_AutoUppercaseInput = True

' Captcha persistence configuration
' ---------------------------------------------------------------------
Dim LBD_Persistence : Set LBD_Persistence = Session
LBD_Configuration_UseApplicationFallback = True

%>

The ASP Captcha library configuration file defines base Captcha settings for the sample.


Please Note

The information on this page is out of date and applies to a deprecated version of BotDetect™ CAPTCHA (v3.0).

An up-to-date equivalent page for the latest BotDetect Captcha release (v4) is BotDetect v4 Captcha documentation index.

General information about the major improvements in the current BotDetect release can be found at the What's New in BotDetect v4.0 page.