React Basic CAPTCHA Code Example

  1. Client-side
  2. Server-side

I. Client-side

The React Captcha Basic code example shows the most basic source code required to protect a React 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 React application.

basic.jsx

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class Basic extends React.Component {

  constructor(props) {
    super(props);
    
    captchaSettings.set({
      captchaEndpoint: '/bdc4-simple-api-react-captcha-example/botdetectcaptcha'
    });
  }

  componentDidMount() {
    const self = this;
    // a global variable that holds validation status of captcha input field,
    // use it for checking validation status when form is submitted
    this.isCorrectCaptchaCode = false;

    // UI captcha validation on blur event by using the custom 'validatecaptcha' event
    // and checking the 'isCorrect' variable to either show error messages
    // or check captcha code input field status when form is submitted
    document.getElementById('captchaCode').addEventListener('validatecaptcha', function (e) {
      // update validation status of captcha code input
      self.isCorrectCaptchaCode = e.detail;
      // display or remove error message
      if (e.detail) {
        document.getElementById('submitButton').removeAttribute('disabled');
      } else {
        document.getElementById('captchaCode').value = 'Incorrect code';
        document.getElementById('submitButton').setAttribute('disabled', true);
      }
    })
  }

  basicFormSubmit(event) {
    // get captcha client-side object
    const captcha = this.captcha.getInstance();
    
    const isCorrect = this.isCorrectCaptchaCode;
    if (isCorrect) {
      // captcha id for validating captcha at server-side
      const captchaId = captcha.captchaId;

      // captcha code input value for validating captcha at server-side
      const captchaCode = document.getElementById('captchaCode').value;

      const postData = {
        captchaId: captchaId,
        captchaCode: captchaCode
      };
      
      const formMess = document.getElementById('form-messages');
      axios.post('/bdc4-simple-api-react-captcha-example/basic-captcha', postData)
        .then(response => {
          if (response.data.success) {
            // captcha validation passed at server-side
            formMess.setAttribute('class', 'alert alert-success');
            formMess.innerHTML = 'CAPTCHA validation passed.';
          } else {
            // captcha validation failed at server-side
            formMess.setAttribute('class', 'alert alert-error');
            formMess.innerHTML = 'CAPTCHA validation falied.';
          }
          captcha.reloadImage();
        }).catch(function (error) {
          throw new Error(error);
        });

    } else {
      formMess.setAttribute('class', 'alert alert-error');
      formMess.innerHTML = 'Captcha code could not be empty.';
    }
    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="basicForm" method="POST" onSubmit={this.basicFormSubmit.bind(this)}>
          <div id="form-messages"></div>
      
          // show captcha image in form
          <Captcha styleName="reactBasicCaptcha" ref={(captcha) => {this.captcha = captcha}} />

          <label>
            <span>Retype the characters from the picture:</span>
            <input name="captchaCode" id="captchaCode" data-correct-captcha/>
          </label>

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

          <button type="submit" id="submitButton" disabled="disabled">Validate</button>
        </form>
      </section>
    )
  }
}

module.exports = Basic;

We first import the Captcha component in the React component and use captchaSettings.set() to configure BotDetect Java Captcha path in captchaEndpoint setting in constructor method.

In the React component render method, we add Captcha protection to the form by redering the Captcha component, set to styleName attribute a Captcha style name defined in botdetect.xml configuration file below, and use ref attribute as shown right above in order to access Captcha element and we will use it to get the BotDetect client-side object later when form is submitted in basicFormSubmit method.

Once we add data-correct-captcha attribute in the captcha code input element, BotDetect Captcha React component 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 (basicFormSubmit method), 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. Serverside

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-BD4_Java_LC.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>reactBasicCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>1</codeLength>
      <helpLinkMode>IMAGE</helpLinkMode>
    </captchaStyle>
  </captchaStyles>
</botdetect>

In WEB-INF/botdetect.xml, we configure some captcha options for our React 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.reactjs.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

React Captcha Component 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.