How To Add BotDetect CAPTCHA Protection to jQuery Application

Please Note

jQuery Captcha Plugin requires the new experimental Simple API that is currently available in BotDetect Java version (4.0.Beta3+) and BotDetect PHP version (4.2.0+). Click here to find out when the Simple API will be available in BotDetect ASP.NET and Classic ASP.

CAPTCHA Integration Steps

  1. Client-side
  2. Server-side

I. Client-side

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 checking user input on blur event at client-side by listening the custom validatecaptcha event:

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

You can also see how BotDetect Captcha protection has been added to a simple HTML form by running the BotDetect Captcha integration code examples comming with the BotDetect download package.

(Please Note: Currently, jQuery Captcha plugin is only supported by BotDetect Java and PHP, but support in ASP.NET version is coming soon.)

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

This step is very important to make sure that BotDetect CAPTCHA library works properly in your jQuery application, so please follow it carefully.

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

    var captcha = $('#botdetect-captcha').captcha({
      captchaEndpoint: '/botdetect-java-captcha-api-path-at-server-side/botdetectcaptcha'
    });

});

When DOM has been loaded, we load jQuery Captcha plugin using .captcha() method. It requires to configure BotDetect Java Captcha path to captchaEndpoint setting. The captcha JavaScript object exposes all Captcha workflow functions and values, we will use it later when form is submitted.

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

  • /botdetect-java-captcha-api-path-at-server-side: is an example path, you need to set exact path to where you have installed BotDetect Java Captcha library before. In case you install BotDetect Java Captcha library at root of your domain, then you won't need to set this path.
  • /botdetectcaptcha: is SimpleCaptchaServlet path, which is described on Register SimpleCaptchaServlet 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/botdetect-java-captcha-api-path-at-server-side/botdetectcaptcha (replace the exact path of your domain). If you see any error messages ("unknown command") thrown by BotDetect Captcha from this url, then you set the right path.

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 can 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 the code described in Step 3 right above.

Validate the Captcha in your jQuery application

Client-side validate the Captcha

BotDetect Captcha jQuery will automatically validate captcha code on blur event 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
  }
})

Please note that, this client-side captcha validation is just an UI validation, it does not protect your form from spammers yet. You are protecting some server-side action, and therefore you need to validate Captcha at a server-side.

Server-side validate the Captcha

$('#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',
    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:

....

import com.captcha.botdetect.web.servlet.SimpleCaptcha;

public class ExampleServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
   
    PrintWriter out = response.getWriter();
    Gson gson = new Gson();
    
    response.setContentType("application/json; charset=utf-8");
    
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());
    
    String captchaId = formDataObj.get("captchaId").getAsString();
    String captchaCode = formDataObj.get("captchaCode").getAsString();
    
    // validate captcha
    SimpleCaptcha captcha = SimpleCaptcha.load(request);
    boolean isHuman = captcha.validate(captchaCode, captchaId);
    
    if (isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }
    
    // the object that stores validation result
    ExampleValidationResult validationResult = new ExampleValidationResult();
    validationResult.setSuccess(isHuman);
    
    try {
      // write the validation result as json string for sending it back to client
      out.write(gson.toJson(validationResult));
    } catch(Exception ex) {
      out.write(ex.getMessage());
    } finally {
      out.close();
    }
  }
}

Finally, we write the validation result as json string for sending it back to client.

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. Server-side

Install BotDetect Java Captcha library on Server-side

Before integrating BotDetect Captcha in your jQuery application, you need to ensure you have installed BotDetect Java 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/java" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/java 
      https://captcha.com/schema/java/botdetect-4.0.beta3.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 WEB-INF/ folder. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.