jQuery Basic CAPTCHA Code Example

  1. Client-side
  2. Server-side

I. Client-side

The jQuery Captcha code example shows the most basic source code required to protect a jQuery application with BotDetect CAPTCHA and validate the user input.

It can be used as a starting point when you first learn how to use BotDetect in your jQuery application.

Download the BotDetect Java CAPTCHA Library and run this example

Downloaded Location

The jQuery Basic CAPTCHA code example is included in the examples/simple-api/bdc4-simple-api-jquery-captcha-example.war file of the download package. When deploying (unpacking) the file you will see the following main source code files:

basic-captcha.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>BotDetect jQuery CAPTCHA Examples</title>
  <link href="styles/styles.css" type="text/css" rel="stylesheet">
</head>
<body>
  <header>
    <div class="header-content"><h1>BotDetect jQuery CAPTCHA Examples</h1></div>
  </header>

  <nav>
    <ul class="nav">
      <li><a href="basic-captcha.html" class="active">Basic Example</a></li>
      <li><a href="contact-captcha.html">Contact Example</a></li>
   </ul>
  </nav>

  <section id="main-content">
    <form id="basicForm" method="POST">
      <div id="form-messages"></div>

      <!-- show Captcha image html-->
      <div id="botdetect-captcha" data-stylename="jqueryBasicCaptcha"></div>

      <label>
        <span>Retype the characters from the picture:</span>
        <!-- captcha code user input textbox -->
        <input 
          type="text" 
          name="captchaCode" 
          id="captchaCode"
          data-correct-captcha
        >
      </label>

      <div class="error captchaCode"></div>

      <button type="submit" id="submitButton" disabled="disabled">Validate</button>
    </form>
  </section>
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="node_modules/jquery-captcha/dist/jquery-captcha.min.js"></script>
  <script src="js/basic.js"></script>
</body>
</html>

Adding Captcha protection to the jQuery form is as simple as declaring an HTML element and set to data-stylename attribute a Captcha style name defined in botdetect.xml configuration file below.

In captcha code input element, we add data-correct-captcha attribute. It will tell BotDetect Captcha jQuery plugin to validate captcha code on blur event.

Finally, do not forget to include the BotDetect Captcha jQuery plugin in your HTML template.

basic.js

$(function() {
  
  // load BotDetect Captcha jQuery  plugin, it requires you to configure 
  // a BotDetect Java Captcha path to captchaEndpoint setting
  var captcha = $('#botdetect-captcha').captcha({
    captchaEndpoint: '/bdc4-simple-api-jquery-captcha-example/botdetectcaptcha'
  });
  
  
  // a global variable that holds validation status of captcha input field, 
  // use it for checking validation status when form is submitted
  var isCorrectCaptchaCode = false;
  
  
  // listening UI captcha validation on captcha code input element's blur event using
  // the custom 'validatecaptcha' event
  $('#captchaCode').on('validatecaptcha', function(event, isCorrect) {
    // update validation status of captcha code input
    isCorrectCaptchaCode = isCorrect;

    // display or remove error message
    if (isCorrect) {
      $('.captchaCode').text('');
      $('#submitButton').attr('disabled', false);
    } else {
      $('.captchaCode').text('Incorrect code');
      $('#submitButton').attr('disabled', true);
    }
  });
  
  
  // validate captcha at server-side when form is submitted
  $('#basicForm').submit(function(event) {
    
    if (isCorrectCaptchaCode) {
      
      // 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: '/bdc4-simple-api-jquery-captcha-example/basic-captcha',
        data: JSON.stringify(postData),
        success: function(response) {
          if (response.success) {
            // captcha validation passed at server-side
            $('#form-messages')
              .removeClass()
              .addClass('alert alert-success')
              .text('CAPTCHA validation passed.');
          } else {
            // captcha validation failed at server-side
            $('#form-messages')
              .removeClass()      
              .addClass('alert alert-error')
              .text('CAPTCHA validation falied.');
          }
        },
        complete: function() {
          // always reload captcha image after validating captcha at server-side 
          // in order to update new captcha code for current captcha id
          captcha.reloadImage();
          
          $('#submitButton').attr('disabled', true);
        },
        error: function(error) {
          throw new Error(error);
        }
      });
      
    } else {
      $('#form-messages')
        .removeClass()      
        .addClass('alert alert-error')
        .text('Captcha code could not be empty.');
    }
    event.preventDefault();
  });
  
});

We first load BotDetect Captcha jQuery plugin, it requires you to configure a BotDetect Java Captcha path to captchaEndpoint setting.

Once we add data-correct-captcha attribute in the captcha code input element, BotDetect Captcha jQuery plugin will then automatically validate captcha code on blue event in default. And to check the UI captcha validation result, we listen the custom validatecaptcha event, which will be fired on captcha code input blur event.

On form submit, we need to send captcha id value and captcha code visitors submitted to server-side to validate Captcha code once at server-side api. Once request finished, we always reload Captcha by calling reloadImage() function of captcha object. This is needed to generate the new captcha code for the current captcha id.

II. Server-side

botdetect.xml

<?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.2.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>jqueryBasicCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>3-5</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

In WEB-INF/botdetect.xml, we configure some captcha options for our jquery basic captcha. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

BasicServlet.java

package com.captcha.botdetect.examples.jquery.basic_form;

import com.captcha.botdetect.web.servlet.SimpleCaptcha;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BasicServlet 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
    BasicValidationResult validationResult = new BasicValidationResult();
    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();
    }
  }
}

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

BasicValidationResult.java

package com.captcha.botdetect.examples.jquery.basic_form;

public class BasicValidationResult {
  private boolean success;

  public BasicValidationResult() {
  }

  public boolean getSuccess() {
    return success;
  }

  public void setSuccess(boolean success) {
    this.success = success;
  }
}

This class is to store Captcha validation result and use it to convert to JSON string using Gson library in BasicServlet.


Please Note

Angular Captcha Module 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.