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.

Installed Location

By default, the React Basic CAPTCHA code example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET\WebApp\SimpleAPI\ReactCaptchaExample

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > ASP.NET Examples > Run .NET Examples

App.js

import React, { Component } from 'react';
import { HashRouter } from 'react-router-dom'
import BaseLayout from './BaseLayout.jsx';
import { captchaSettings } from 'reactjs-captcha';


class App extends Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 'BotDetectCaptcha.ashx'
    });
  }


  render() {
    return (
      <HashRouter>
        <BaseLayout />
      </HashRouter>
    );
  }
}

export default App;

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

basic.jsx

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

class Basic extends React.Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    // 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) {
      // display or remove error message
      let isCaptchaCodeCorrect = event.detail;

      if (isCaptchaCodeCorrect) {
        document.getElementsByClassName('captcha-code-error')[0].innerHTML = '';
      } else {
        document.getElementsByClassName('captcha-code-error')[0].innerHTML = 'Incorrect code';
      }
    });
  }

  basicFormSubmit(event) {
   
    // captcha id for validating captcha at server-side
    let captchaId = this.captcha.getCaptchaId();

    // captcha code input value for validating captcha at server-side
    let captchaCode = this.captcha.getCaptchaCode();

    let postData = {
      captchaId: captchaId,
      captchaCode: captchaCode
    };

    let self = this;
    let formMessage = document.getElementById('form-messages');

    axios.post('form/BasicHandler.ashx', postData)
        .then(response => {
          if (response.data.success) {
            // captcha validation passed at server-side
            formMessage.setAttribute('class', 'alert alert-success');
            formMessage.innerHTML = 'CAPTCHA validation passed.';
          } else {
            // captcha validation failed at server-side
            formMessage.setAttribute('class', 'alert alert-error');
            formMessage.innerHTML = 'CAPTCHA validation falied.';
          }
          self.captcha.reloadImage();
        }).catch(function (error) {
          throw new Error(error);
        });

    event.preventDefault();
  }

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

          <Captcha styleName="reactBasicCaptcha" 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 captcha-code-error"></div>

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

export default Basic;

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/net" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/net 
     https://captcha.com/schema/net/botdetect-4.4.0.xsd">

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

</botdetect>

In config/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 SimpleCaptcha configuration options page.

BasicHandler.ashx

<%@ WebHandler Language="C#" Class="BasicHandler" %>

using System;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BotDetect.Web;


public class BasicHandler : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        if (HttpContext.Current.Request.HttpMethod == "POST")
        {
            string dataJson = new StreamReader(context.Request.InputStream).ReadToEnd();

            Dictionary<string, string> formDataObj = new Dictionary<string, string>();
            formDataObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataJson);

            string captchaId = formDataObj["captchaId"];
            string captchaCode = formDataObj["captchaCode"];

            // validate captcha
            SimpleCaptcha captcha = new SimpleCaptcha();
            bool isHuman = captcha.Validate(captchaCode, captchaId);

            if (isHuman)
            {
                // Captcha validation passed
                // TODO: do whatever you want here
            }

            // the object that stores validation result
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>();
            validationResult.Add("success", isHuman);

            // write the validation result as json string for sending it back to client
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(validationResult));
        }
        else
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("HTTP GET request is not allowed.");
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

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.

Please Note

React Captcha Component requires the new experimental Simple API that is currently available in BotDetect Java v4.0.Beta3+, BotDetect PHP v4.2.0+, as well as in BotDetect ASP.NET v4.4.0 build for legacy .NET.
The Simple API for ASP.NET Core will be available in the BotDetect ASP.NET v4.4.1 that will be released in few weeks time.