CAPTCHAs are an integral part of website security. People complete millions of CAPTCHA tests online every day.

If you haven't implemented CAPTCHA validation on your website, it could create a big problem for you, setting you up as a target for spammers.

Here's everything you need to know about CAPTCHAs and how you can easily implement them with HTML, CSS, and JavaScript.

What Is CAPTCHA?

CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart." Luis von Ahn, Manuel Blum, Nicholas J. Hopper, and John Langford coined this term in 2003. It's a type of challenge-response test that websites use to determine whether the user is human or not.

CAPTCHAs add security to websites by providing challenges that are difficult for bots to perform but relatively easy for humans. For example, identifying all the images of a car from a set of multiple images is difficult for bots but simple enough for human eyes.

The idea of CAPTCHA originates from the Turing Test. A Turing Test is a method to test whether a machine can think like a human or not. You can think of a CAPTCHA test as a "reverse Turing Test" since it challenges a human to prove they are not a computer.

Why Your Website Needs CAPTCHA Validation

CAPTCHAs are important for many reasons. You can use them to stop bots from submitting spam and harmful content in forms. They can also help stop some forms of hacking attacks.

Even companies like Google use CAPTCHA to protect their systems from spam attacks.

HTML CAPTCHA Code

The code used in this project is available in a GitHub repository and is free for you to use under the MIT license. If you want to have a look at a live version of this project, you can check out this demo.

In this project, you will be adding CAPTCHA to an HTML form. Use the following code to add CAPTCHA in HTML:

        <!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
    <div class="center">
        <h1 id="captchaHeading">
            Captcha Validator Using HTML, CSS and JavaScript
        </h1>

        <div id="captchaBackground">
            <canvas id="captcha">captcha text</canvas>
            <input id="textBox" type="text" name="text">

            <div id="buttons">
                <input id="submitButton" type="submit">
                <button id="refreshButton" type="submit">Refresh</button>
            </div>

            <span id="output"></span>
        </div>
    </div>

    <script src="script.js"></script>
</body>

</html>

This code mainly consists of seven elements:

  • <h1 id="captchaHeading"> <h1>: This element displays the heading of the CAPTCHA form.
  • <canvas id="captcha"> </canvas>: This element displays the CAPTCHA text.
  • <input id="textBox" type="text" name="text"> - This element creates an input box to enter the CAPTCHA.
  • <input id="submitButton" type="submit">: This button submits the form and checks whether the CAPTCHA and the typed text are the same.
  • <button id="refreshButton" type="submit"> </button>: This button refreshes the CAPTCHA.
  • <span id="output"> </span>: This element displays the output after validating the entered text with CAPTCHA.
  • <div class="center"> </div>: This is the parent element that contains all the other elements.

This CAPTCHA HTML template links to CSS and JavaScript files via the link and script elements respectively. You must add the link tag inside the head and the script tag at the end of the body.

There are many HTML tags and attributes, and remembering them all can be overwhelming. You can always refer to an HTML cheat sheet to get a quick refresher on HTML tags and attributes.

You can also integrate this code with existing forms on your website.

CSS CAPTCHA Code

You can use CSS—Cascading Style Sheets—to style HTML elements. Use the following CSS code to style the CAPTCHA validation form:

        @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

body {
    background-color: #232331;
    font-family: 'Roboto', sans-serif;
}

#captchaBackground {
    height: 220px;
    width: 250px;
    background-color: #2d3748;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

#captchaHeading {
    color: white;
}

#captcha {
    height: 80%;
    width: 80%;
    font-size: 30px;
    letter-spacing: 3px;
    margin: auto;
    display: block;
}

.center {
    display: flex;
    flex-direction: column;
    align-items: center;
}

#submitButton {
    margin-top: 2em;
    margin-bottom: 2em;
    background-color: #08e5ff;
    border: 0px;
    font-weight: bold;
}

#refreshButton {
    background-color: #08e5ff;
    border: 0px;
    font-weight: bold;
}

#textBox {
    height: 25px;
}

.incorrectCaptcha {
    color: #FF0000;
}

.correctCaptcha {
    color: #7FFF00;
}

Add or remove CSS properties from this code according to your preference. You can also give an elegant look to the form container using the CSS box-shadow property.

CAPTCHA Validation Using JavaScript

You need to use JavaScript to add functionality to a webpage. Start by fetching references to the elements you’ll need to work with including the canvas and input box. Use the document.getElementById() function to do this:

        let captchaText = document.getElementById('captcha');
var ctx = captchaText.getContext("2d");
ctx.font = "30px Roboto";
ctx.fillStyle = "#08e5ff";

let userText = document.getElementById('textBox');
let submitButton = document.getElementById('submitButton');
let output = document.getElementById('output');
let refreshButton = document.getElementById('refreshButton');

Here, you're using document.getElementById() to select an element from the document by its ID.

To generate the CAPTCHA text, you’ll need to pick some random characters, and there are various approaches you can take. One of the simplest is to store a set of potential characters in an array to choose from:

        var captchaStr = "";

let alphaNums = ['A', 'B', 'C', 'D', 'E', 'F', 'G',
                 'H', 'I', 'J', 'K', 'L', 'M', 'N',
                 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
                 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                 'j', 'k', 'l', 'm', 'n', 'o', 'p',
                 'q', 'r', 's', 't', 'u', 'v', 'w',
                 'x', 'y', 'z', '0', '1', '2', '3',
                 '4', '5', '6', '7', '8', '9'];

Write a function to generate a new CAPTCHA. You can call this function immediately to create a CAPTCHA when the page loads. You can also call it to regenerate the CAPTCHA if the user presses the Refresh button.

Start by building a new array from random characters in alphaNums. Loop a fixed number of times—7, in this case—and add a new random character from alphaNums in each iteration. You can then write the final array, as a string, to the canvas using fillText:

        function generate_captcha() {
   let emptyArr = [];

   for (let i = 1; i <= 7; i++) {
       emptyArr.push(alphaNums[Math.floor(Math.random() * alphaNums.length)]);
   }

   captchaStr = emptyArr.join('');

   ctx.clearRect(0, 0, captchaText.width, captchaText.height);
   ctx.fillText(captchaStr, captchaText.width/4, captchaText.height/2);

   output.innerHTML = "";
}

generate_captcha();

Note that this function clears the canvas and resets any output, both of which are important for refreshing the CAPTCHA text.

Complete the core functionality by checking the user’s entry against the original CAPTCHA text. You can define a function to do this:

        
function check_captcha() {
    if (userText.value === captchaStr) {
        output.className = "correctCaptcha";
        output.innerHTML = "Correct!";
    } else {
        output.className = "incorrectCaptcha";
        output.innerHTML = "Incorrect, please try again!";
    }
}

And call that function in response to the Enter key or a press of the Submit button:

        userText.addEventListener('keyup', function(e) {
    if (e.key === 'Enter') {
       check_captcha();
    }
});

submitButton.addEventListener('click', check_captcha);

Finally, handle the refresh functionality. Just connect the button’s submit event to the generate_captcha() function to do so:

        refreshButton.addEventListener('click', generate_captcha);
    

Output of the CAPTCHA Validator Project

Now you have a fully functional CAPTCHA validation form. You can also clone the GitHub repository of this CAPTCHA Validator project. After cloning the repository, run the project and you'll see the following output:

CAPTCHA Validator form

When you enter the correct CAPTCHA code in the input box, it will display the following output:

CAPTCHA Validator form correct CAPTCHA

When you enter an incorrect CAPTCHA code in the input box, it will display the following output:

CAPTCHA Validator form Incorrect CAPTCHA

Secure Your Website With CAPTCHAs

In the past, many organizations and businesses have suffered heavy losses like data breaches, spam attacks, etc., as a result of not having CAPTCHA forms on their websites. It's highly recommended to add CAPTCHA to your website, as it adds a security layer to prevent the website from cyber criminals.

Google also launched a free service called "reCAPTCHA" that helps in protecting websites from spam and abuse. CAPTCHA and reCAPTCHA seem similar, but they're not quite the same thing. Sometimes CAPTCHAs feel frustrating and difficult to understand for many users. Although, there's an important reason why they're made to be difficult.