React Form CAPTCHA Code Example

  1. Client-side
  2. Server-side

I. Client-side

The React Form Captcha code example shows how to add BotDetect CAPTCHA protection to a typical React form.

Captcha validation is integrated with other form fields validation, and only submissions that meet all validation criteria are accepted.

This kind of validation could be used on various types of public forms which accept messages, and are at risk of unwanted automated submissions.

For example, it could be used to ensure bots can't submit anything to a contact form, add guestbook entries, blog post comments or anonymous message board / forum replies.

contact.jsx

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

class Contact extends React.Component {

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

  componentDidMount() {
    let self = this;

    // error messages of input fields
    const errorMessages = {
      name: 'Name must be at least 3 characters.',
      email: 'Email is invalid.',
      subject: 'Subject must be at least 10 characters.',
      message: 'Message must be at least 10 characters.',
      captchaCode: 'Invalid code.'
    };

    // global variables that holds validation status of captcha input field,
    // use them for checking validation status when form is submitted
    self.isValidName = false;
    self.isValidEmail = false;
    self.isValidSubject = false;
    self.isValidMessage = false;
    self.isCorrectCaptchaCode = false;


    function validateName() {
      const name = document.getElementById('name').value;
      self.isValidName = (name.length >= 3);
      if (self.isValidName) {
        document.getElementsByClassName('name')[0].innerHTML = '';
      } else {
        document.getElementsByClassName('name')[0].innerHTML = errorMessages.name;
      }
    }

    function validateEmail() {
      const email = document.getElementById('email').value;
      const emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      self.isValidEmail = emailRegEx.test(email);
      if (self.isValidEmail) {
        document.getElementsByClassName('email')[0].innerHTML = '';
      } else {
        document.getElementsByClassName('email')[0].innerHTML = errorMessages.email;
      }
    }

    function validateSubject() {
      const subject = document.getElementById('subject').value;
      self.isValidSubject = (subject.length >= 10);
      if (self.isValidSubject) {
        document.getElementsByClassName('subject')[0].innerHTML = '';
      } else {
        document.getElementsByClassName('subject')[0].innerHTML = errorMessages.subject;
      }
    }

    function validateMessage() {
      const message = document.getElementById('message').value;
      self.isValidMessage = (message.length >= 10);
      if (self.isValidMessage) {
        document.getElementsByClassName('message')[0].innerHTML = '';
      } else {
        document.getElementsByClassName('message')[0].innerHTML = errorMessages.message;
      }
    }

    // validate input fields on blur event'
    document.getElementById('name').addEventListener('blur', validateName);
    document.getElementById('email').addEventListener('blur', validateEmail);
    document.getElementById('subject').addEventListener('blur', validateSubject);
    document.getElementById('message').addEventListener('blur', validateMessage);

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

  submitForm(event) {
    if (this.isValidName && this.isValidEmail && this.isValidSubject
        && this.isValidMessage && this.isCorrectCaptchaCode) {
      // form is valid
      // we send contact data as well as captcha data to server-side for
      // validating once again before they are inserted into database
     
      // get captcha client-side object
      const captcha = this.captcha.getInstance();
      
      // 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 = {
        name: document.getElementById('name').value,
        email: document.getElementById('email').value,
        subject: document.getElementById('subject').value,
        message: document.getElementById('message').value,
        captchaId: captchaId,
        captchaCode: captchaCode
      };

      axios.post('/bdc4-simple-api-react-captcha-example/contact', postData)
        .then(response => {
          if (response.data.success) {
            // captcha, other form data passed and the data is also stored in database
            // show success message
            document.getElementById('form-messages').setAttribute('class', 'alert alert-success');
            document.getElementById('form-messages').innerHTML = 'Your message was sent successfully!.';
          } else {
            // form validation failed
            document.getElementById('form-messages').setAttribute('class', 'alert alert-error');
            document.getElementById('form-messages').innerHTML = 'An error occurred while sending your message, please try again.';
          }
          captcha.reloadImage();
          document.getElementById('submitButton').setAttribute('disabled', true);
        }).catch(error => {
          document.getElementById('submitButton').setAttribute('disabled', true);
          throw new Error(error);
        });
    } else {
      // form is invalid
      document.getElementById('form-messages').setAttribute('class', 'alert alert-error');
      document.getElementById('form-messages').innerHTML = 'The form fields could not be empty.';
    }
    
    event.preventDefault();
  }

  render() {
    return (
      <div id="main-content">
        <form id="contactForm" method="POST" onSubmit={this.submitForm.bind(this)}>
          <div id="form-messages"></div>

          <label>
            <span>Name:</span>
            <input type="text" id="name" name="name"/>
          </label>
          <div className="error name"></div>


          <label>
            <span>Email</span>
            <input type="email" id="email" name="email"/>
          </label>
          <div className="error email"></div>


          <label>
            <span>Subject:</span>
            <input type="text" id="subject" name="subject"/>
          </label>
          <div className="error subject"></div>


          <label>
            <span>Message:</span>
            <textarea id="message" name="message"></textarea>
          </label>
          <div className="error message"></div>


          // show captcha image in form
          <Captcha styleName="reactFormCaptcha" ref={(captcha) => {this.captcha = captcha}} />

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

          <button type="submit" id="submitButton" disabled="disabled" className="btn btn-primary">Send
          </button>
        </form>
      </div>
    )
  }
}

module.exports = Contact;

Just like React Basic Captcha example, we also need to configure BotDetect Java Captcha path to captchaEndpoint setting using captchaSettings.set() method, add Captcha protection to the form by redering the Captcha component, as well as use ref attribute to access Captcha element in order to get Captcha client-side object when form is submitted.

In captcha code input element, we also add data-correct-captcha attribute. 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.

Beside the captcha code input field, the example form contains three other fields such as name, email, subject, message. And in the React's componentDidMount method, we define validation functions and perform blur validation for these fields

On form submit (submitForm 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-4.0.beta3.3.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>reactFormCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>4-6</codeLength>
      <codeStyle>ALPHANUMERIC</codeStyle>
    </captchaStyle>
  </captchaStyles>
</botdetect>

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

ContactServlet.java

package com.captcha.botdetect.examples.reactjs.contact_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 java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContactServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    Gson gson = new Gson();
    Map<String, String> errors = new HashMap<String, String>();

    response.setContentType("application/json; charset=utf-8");

    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());

    String name = formDataObj.get("name").getAsString();
    String email = formDataObj.get("email").getAsString();
    String subject = formDataObj.get("subject").getAsString();
    String message = formDataObj.get("message").getAsString();
    String captchaId = formDataObj.get("captchaId").getAsString();
    String captchaCode = formDataObj.get("captchaCode").getAsString();

    if (!isValidName(name)) {
      errors.put("name", "Name must be at least 3 characters.");
    }

    if (!isValidEmail(email)) {
      errors.put("email", "Email is invalid.");
    }

    if (!isValidSubject(subject)) {
      errors.put("message", "Subject must be at least 10 characters.");
    }

    if (!isValidMessage(message)) {
      errors.put("message", "Message must be at least 10 characters.");
    }

    if (!isCaptchaCorrect(request, captchaCode, captchaId)) {
      errors.put("captchaCode", "CAPTCHA validation failed.");
    }

    if (errors.isEmpty()) {
      // everything is ok
      // TODO: Insert form data into your database
    }

    // the object that stores validation result
    ContactValidationResult validationResult = new ContactValidationResult();
    validationResult.setSuccess(errors.isEmpty());
    validationResult.setErrors(errors);

    try {
      // write the validation result as json string for sending it back to client
      out.write(gson.toJson(validationResult));
    } finally {
      out.close();
    }
  }


  private boolean isCaptchaCorrect(HttpServletRequest request, String captchaCode, String captchaId) {
    SimpleCaptcha captcha = SimpleCaptcha.load(request);
    return captcha.validate(captchaCode, captchaId);
  }

  private boolean isValidName(String name) {
    if (name == null) {
      return false;
    }
    return (name.length() >= 3);
  }

  private boolean isValidEmail(String email) {
    if (email == null) {
      return false;
    }
    return email.matches("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$");
  }

  private boolean isValidSubject(String subject) {
    if (subject == null) {
      return false;
    }
    return (subject.length() > 9) && (subject.length() < 255);
  }

  private boolean isValidMessage(String message) {
    if (message == null) {
      return false;
    }
    return (message.length() > 9) && (message.length() < 255);
  }
}

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.

ContactValidationResult.java

package com.captcha.botdetect.examples.react.contact_form;

import java.util.HashMap;
import java.util.Map;

public class ContactValidationResult {
  private boolean success;
  private Map<String, String> errors;

  public ContactValidationResult() {
    errors = new HashMap<String, String>();
  }

  public boolean getSuccess() {
    return success;
  }

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

  public Map<String, String> getErrors() {
    return errors;
  }

  public void setErrors(Map<String, String> errors) {
    this.errors = errors;
  }
}

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

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.