How to add Capcha in HTML, CSS and JavaScript

Secure your websites with CAPTCHA validation.

Nowadays CAPTCHAs are an integral part of website security. Millions of CAPTCHA tests are completed 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 to spammers.

Here’s everything you need to know about CAPTCHAs and how you can easily implement them on your website using HTML, CSS, and JavaScript.

What Is CAPTCHA?

CAPTCHA stands for “Completely Automated Public Turing test to tell Computers and Humans Apart.” This term was coined in 2003 by Luis von Ahn, Manuel Blum, Nicholas J. Hopper, and John Langford. It’s a type of challenge-response test which is used 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. Interestingly, a CAPTCHA test can be called a “reverse Turing Test” since in this case, the computer creates the test that challenges humans.

Why Your Website Needs CAPTCHA Validation?

CAPTCHAs are mainly used to prevent bots from automatically submitting forms with spam and other harmful content. Even companies like Google use it to prevent their system from spam attacks. Here are some of the reasons why your website stands to benefit from CAPTCHA validation:

  • CAPTCHAs help to prevent hackers and bots from spamming the registration systems by creating fake accounts. If they aren’t prevented, they can use those accounts for nefarious purposes.
  • CAPTCHAs can forbid brute force log-in attacks from your website which hackers use to try logging in using thousands of passwords.
  • CAPTCHAs can restrict bots from spamming the review section by providing false comments.
  • CAPTCHAs aid in preventing ticket inflation as some people purchase a large number of tickets for reselling. CAPTCHA can even prevent false registrations to free events.
  • CAPTCHAs can restrict cyber crooks from spamming blogs with dodgy comments and links to harmful websites.

There are many more reasons that support integrating CAPTCHA validation into your website. You can do so with the following code.


HTML CAPTCHA Code:

<!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 7 elements:

  • <h1 id=”captchaHeading”> <h1>: This element is used to display the heading of the CAPTCHA form.
  • <canvas id=”captcha”> </canvas>: This element is used to display the CAPTCHA text.
  • <input id=”textBox” type=”text” name=”text”> – This element is used to create an input box to type the CAPTCHA.
  • <input id=”submitButton” type=”submit”>: This button submits the form and check whether the CAPTCHA and the typed text is same or not.
  • <button id=”refreshButton” type=”submit”> </button>: This button is used to refresh the CAPTCHA.
  • <span id=”output”> </span>: This element is used to display the output according to the entered text.
  • <div class=”center”> </div>: This is the parent element that contains all the other elements.

CSS and JavaScript files are linked to this HTML page through the <link rel=”stylesheet” type=”text/css” href=”styles.css”> and <script src=”script.js”> </script> elements respectively. You must add the link tag inside the head tag and script tag at the end of the body.


CSS CAPTCHA Code:

@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;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.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.


JavaScript CAPTCHA Code:

// document.querySelector() is used to select an element from the document using its ID
let captchaText = document.querySelector('#captcha');
var ctx = captchaText.getContext("2d");
ctx.font = "30px Roboto";
ctx.fillStyle = "#08e5ff";

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

// alphaNums contains the characters with which you want to create the CAPTCHA
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'];
let emptyArr = [];
// This loop generates a random string of 7 characters using alphaNums
// Further this string is displayed as a CAPTCHA
for (let i = 1; i <= 7; i++) {
emptyArr.push(alphaNums[Math.floor(Math.random() * alphaNums.length)]);
}
var c = emptyArr.join('');
ctx.fillText(emptyArr.join(''),captchaText.width/4, captchaText.height/2);

// This event listener is stimulated whenever the user press the "Enter" button
// "Correct!" or "Incorrect, please try again" message is
// displayed after validating the input text with CAPTCHA
userText.addEventListener('keyup', function(e) {
// Key Code Value of "Enter" Button is 13
if (e.keyCode === 13) {
if (userText.value === c) {
output.classList.add("correctCaptcha");
output.innerHTML = "Correct!";
} else {
output.classList.add("incorrectCaptcha");
output.innerHTML = "Incorrect, please try again";
}
}
});
// This event listener is stimulated whenever the user clicks the "Submit" button
// "Correct!" or "Incorrect, please try again" message is
// displayed after validating the input text with CAPTCHA
submitButton.addEventListener('click', function() {
if (userText.value === c) {
output.classList.add("correctCaptcha");
output.innerHTML = "Correct!";
} else {
output.classList.add("incorrectCaptcha");
output.innerHTML = "Incorrect, please try again";
}
});
// This event listener is stimulated whenever the user press the "Refresh" button
// A new random CAPTCHA is generated and displayed after the user clicks the "Refresh" button
refreshButton.addEventListener('click', function() {
userText.value = "";
let refreshArr = [];
for (let j = 1; j <= 7; j++) {
refreshArr.push(alphaNums[Math.floor(Math.random() * alphaNums.length)]);
}
ctx.clearRect(0, 0, captchaText.width, captchaText.height);
c = refreshArr.join('');
ctx.fillText(refreshArr.join(''),captchaText.width/4, captchaText.height/2);
output.innerHTML = "";
});

Now you have a fully functional CAPTCHA validation form! If you want to have a look at the complete code, you can clone the GitHub repository of this CAPTCHA-Validator Project. After cloning the repository, execute the HTML file and you’ll get the following output:

When you enter the correct CAPTCHA code in the input box, the following output will be displayed:

When you enter any incorrect CAPTCHA code in the input box, the following output will be displayed:

Make Your Website Secure 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 cybercriminals.

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 as to why they’re made to be difficult.