How To Add BotDetect CAPTCHA Protection to jQuery Application

BotDetect CAPTCHA works in China -- and it does not stalk you around! Read more...

CAPTCHA Integration Steps

  1. Implementation
  2. Configuration

I. Implementation

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 also see how BotDetect Captcha protection has been added to a simple HTML form by running the BotDetect Captcha integration code examples coming 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.

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();
});
  • 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 UI 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',
    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 a Servlet looks in this way:
....

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();
    }
  }
}

  • Server-side Captcha validation in a Spring MVC Controller looks in this way:
...
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

@Controller
public class ExampleController {

  @RequestMapping(value = "basic-captcha", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
  @ResponseBody
  public String exampleCaptcha(HttpServletRequest request) {
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = null;
    boolean result = false;

    try {
      formDataObj = (JsonObject) parser.parse(request.getReader());
    } catch (IOException ex) { }

    if (formDataObj != null) {
      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);
      
      result = isHuman;
    }

    return "{\"success\":" + result.toString() + "}";
  }
}

  • Server-side Captcha validation in a Struts Action looks in this way:
...
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

public class ExampleAction {

  private boolean success = false;

  public boolean isSuccess() {
    return success;
  }

  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    
    if (!request.getMethod().equalsIgnoreCase("post")) {
      return Action.ERROR;
    }

    Map<String, String> mapParams = request.getParameterMap();
    Set<String> setKeys = mapParams.keySet();
    Iterator<String> temp = setKeys.iterator();
    String data = temp.next();

    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(data);

    if (formDataObj != null) {
      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);
      
      this.success = isHuman;
    }

    return Action.SUCCESS;
  }
}

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. Configuration

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.5.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.

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.