How To Add BotDetect CAPTCHA Protection to jQuery Application

Unlike Recaptcha the Stalker -- BotDetect CAPTCHA works in China! Licensable source-code; self-hosted -- doesn't stalk -- nor does it slurp your form-data! Think: GDPR & LGPD!

CAPTCHA Integration Steps

  1. Integration in jQuery application
  2. Captcha Generator server-side configuration

I. Integration in jQuery app

BotDetect Captcha protection can be added to your jQuery applications using the BotDetect CAPTCHA jQuery Plugin. Displaying the Captcha challenge can be as simple as:

<div id="botdetect-captcha" data-stylename="exampleCaptcha"></div>

and using validateUnsafe(callback) method to validate Captcha code on form submit:

// On form submit
$('#exampleForm').submit(function(event) {

  captcha.validateUnsafe(function(isCaptchaCodeCorrect) {

    if (isCaptchaCodeCorrect) {
      // Captcha code is correct
    } else {
      // Captcha code is incorrect
    }
    
  });

  event.preventDefault();
});

You can see how BotDetect Captcha protection is added to a simple HTML form by running the BotDetect Captcha integration code examples coming with the each BotDetect product's free download package.

Follows the step by step guide on how to integrate BotDetect into your jQuery application. Backend related code snippets come in 3 different techs (.NET, Java & PHP) in order to cover whatever is the technology of your choice.

Install BotDetect CAPTCHA jQuery Plugin

Step 1: Install BotDetect Captcha jQuery Plugin

Step 2: Include BotDetect Captcha jQuery Plugin in your web app

<script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script>

Step 3: Load BotDetect Captcha jQuery Plugin in your application

The following step ensures that BotDetect CAPTCHA library works properly in your jQuery application. Please follow it carefully.

$(document).ready(function() {
    // DOM ready

    var captcha = $('#botdetect-captcha').captcha({
      captchaEndpoint: 'captcha-endpoint/BotDetectCaptcha.ashx'
    });

});

When DOM is loaded, we load jQuery Captcha plugin using the .captcha() method -- passing the captchaEndpoint setting which represents the path where BotDetect ASP.NET Captcha responds. The captcha JavaScript object exposes all Captcha workflow functions and vars that we will use later during the form submission part of the workflow.

Before you set the path to captchaEndpoint setting, we need to clarify what we set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect ASP.NET Captcha library. If you deployed BotDetect ASP.NET Captcha library in the root of your domain, then you don't need to set this path.
  • /BotDetectCaptcha.ashx: is SimpleCaptchaHandler path, which is described on Register BotDetect HttpHandler for CAPTCHA Requests guide below.

To ensure that you have set a right path to captchaEndpoint setting, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/BotDetectCaptcha.ashx (replace the exact path of your domain). If this results with an error message ("unknown command") then you set the right path, since that is the BotDetect Captcha who responded error (when you fail to set correct path, then your server will respond with 404 instead). Please note, in order to perform this check, BotDetect Captcha Generator needs to be installed & deployed to your server.

Display BotDetect CAPTCHA In Your HTML Template

Displaying the Captcha challenge can be as simple as:

<div id="botdetect-captcha" data-stylename="exampleCaptcha"></div>

You simply declare a HTML element and assign data-stylename attribute a captcha style name defined in botdetect.xml configuration file.

The captcha html markup will be displayed as soon as you load the jQuery Captcha plugin in your application as described in the Step 3 above.

Captcha Validation

Client-side Captcha validation in your jQuery application

BotDetect Captcha jQuery Plugin provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit:
// On form submit
$('#exampleForm').submit(function(event) {

  captcha.validateUnsafe(function(isCaptchaCodeCorrect) {

    if (isCaptchaCodeCorrect) {
      // Captcha code is correct
    } else {
      // Captcha code is incorrect
    }
    
  });

  event.preventDefault();
});

OR:

  • Using data-correct-captcha directive attribute to validate Captcha code on blur event:

You need to add the data-correct-captcha attribute in the captcha code input element. BotDetect Captcha jQuery will then automatically validate captcha code on blur event.

<input
  type="text"
  name="captchaCode"
  id="captchaCode"
  data-correct-captcha
>

And you can check the captcha validation result by listing the custom validatecaptcha event as the code shown below.

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) {
  if (isCorrect) {
    // UI Captcha validation passed
  } else {
    // UI Captcha validation failed
  }
})

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

Server-side Captcha validation

$('#exampleForm').submit(function(event) {
  
  // captcha id for validating captcha at server-side
  var captchaId = captcha.getCaptchaId();

  // captcha code input value for validating captcha at server-side
  var captchaCode = $('#captchaCode').val();

  var postData = {
    captchaId: captchaId,
    captchaCode: captchaCode
  };

  $.ajax({
    method: 'POST',
    url: '/your-server-side-api-url',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(postData),
    success: function(response) {
      if (response.success) {
        // captcha validation passed at server-side
      } else {
        // captcha validation failed at server-side
      }
    },
    complete: function() {
      // we should reload captcha image after server-side validation is completed
      // in order to update new captcha code for current captcha id
      captcha.reloadImage();
    }
  });
 
});

To validate Captcha at server-side, we need to send captchaId property of captcha JavaScript object and captcha code visitor submited to server-side.

Once request finished, we always reload Captcha by calling the reloadImage() function of captcha JavaScript object. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using Validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.


  • Server-side Captcha validation in Web API 2:
using BotDetect.Web;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace ProductApp.Controllers
{
    public class ExampleController : ApiController
    {
        // POST api/example
        public HttpResponseMessage Post([FromBody]Models.BasicForm value)
        {
            // validate captcha
            SimpleCaptcha captcha = new SimpleCaptcha();
            bool isHuman = captcha.Validate(value.CaptchaCode, value.CaptchaId);

            if (isHuman)
            {
                // Captcha validation passed
                // TODO: do whatever you want here
            }

            // the object that stores validation result
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>();
            validationResult.Add("success", isHuman);

            // write the validation result as json string for sending it back to client
            string jsonString = JsonConvert.SerializeObject(validationResult);
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            return response;
        }
    }
}

  • Server-side Captcha validation in a Generic Handler:
<%@ WebHandler Language="C#" Class="BasicHandler" %>
using System;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BotDetect.Web;

public class BasicHandler : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        if (HttpContext.Current.Request.HttpMethod == "POST")
        {
            string dataJson = new StreamReader(context.Request.InputStream).ReadToEnd();

            Dictionary<string, string> formDataObj = new Dictionary<string, string>();
            formDataObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataJson);

            string captchaId = formDataObj["captchaId"];
            string captchaCode = formDataObj["captchaCode"];

            // validate captcha
            SimpleCaptcha captcha = new SimpleCaptcha();
            bool isHuman = captcha.Validate(captchaCode, captchaId);

            if (isHuman)
            {
                // Captcha validation passed
                // TODO: do whatever you want here
            }

            // the object that stores validation result
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>();
            validationResult.Add("success", isHuman);

            // write the validation result as json string for sending it back to client
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(validationResult));
        }
    }
}

Display Captcha error message in your HTML template

$('#captchaCode').on('validatecaptcha', function(event, isCorrect) {
  if (!isCorrect) {
    $('#message').text('Incorrect captcha code')
  }
});

To display captcha error message, simply listen the custom validatecaptcha event, which will be fired on captcha code input element's blur event and check the second argument (i.e isCorrect in the code above) of the callback function. If it returns false, this means that UI captcha validation failed.


II. Captcha Generator server-side configuration

Install BotDetect ASP.NET Captcha library on Server-side

Before integrating BotDetect Captcha in your jQuery application, you need to ensure you have installed BotDetect ASP.NET Captcha library on your server where your jQuery application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/net" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/net 
      https://captcha.com/schema/net/botdetect-4.4.0.xsd">

  <captchaStyles>
    
    <captchaStyle>
      <name>exampleCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>6</codeLength>
    </captchaStyle>

    <captchaStyle>
      <name>loginCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>4-6</codeLength>
      <codeStyle>Alphanumeric</codeStyle>
    </captchaStyle>

  </captchaStyles>

</botdetect>

To configure captcha options, you need to create botdetect.xml configuration file (with xml content like the one above this) in root folder of your project. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Please Note

jQuery Captcha Plugin requires the new experimental Simple API that is currently available in BotDetect Java v4.0.Beta3+, BotDetect PHP v4.2.0+, as well as in BotDetect ASP.NET v4.4.0 build for legacy .NET.
The Simple API for ASP.NET Core will be available in the BotDetect ASP.NET v4.4.1 that will be released in few weeks time.