Create Custom Captcha in HTML CSS & JavaScript
Hey friends, today in this blog, you’ll learn how to create Custom Captcha in HTML CSS & JavaScript. In the earlier blog, I have shared how to Detect User Browser using JavaScript, and it’s time to create a simple captcha program. Mostly, Captcha is used on the comment or contact form of the websites to restrict robots (bot) from commenting on a blog post or sending a message to the admin. There can be random images or codes in the captcha, and the users must have to select correct images or match the codes to complete their task. In this small project [Custom Captcha in JavaScript], there is an image with the random 6 characters and numbers. You can also refresh the captcha code and get a new one using the reload button. In the input field, you have to enter the captcha codes that are shown on the image. If your codes matched with the captcha codes, then there is appears a success message else there appears an error message. If you’ve matched the codes, then after 4 seconds there will be generated a new one captcha code. Recommended Book: Rich Dad Poor Dad Pdf I hope you liked this simple captcha program and want to get source codes but don’t worry I have given codes and source code files at the bottom of this page from where you can copy-paste codes the source code files. But before copying codes, let’s understand the basic codes and concepts of this program. At first, in the JavaScript file, I have stored all characters and numbers in the array, then inside for loop, using Math.random() function I got 6 random characters from the given array. And passed these codes or characters in the captcha by adding space between each character. After this, I got user-entered values, split them, and joined them with space (‘ ‘) so users don’t need to enter spaces to match the codes. Once I joined the user values then I matched this user value with the captcha codes. If the value is not matched I’ve shown an error message, and if the value is matched I’ve shown a success message and generate the new random codes after 4 seconds using the setTimeout() function.
Create Custom Captcha in JavaScript [Source Codes]
To create this program [Custom Captcha in JavaScript]. First, you need to create three Files: HTML, CSS & JavaScript File. After creating these files just paste the following codes into your file. First, create an HTML file with the name of index.html and paste the given codes into your HTML file. You’ve to create a file with .html extension and remember the image that is used on this program will not appear.
Captcha in JavaScript Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.
const captcha = document.querySelector(".captcha"), reloadBtn = document.querySelector(".reload-btn"), inputField = document.querySelector(".input-area input"), checkBtn = document.querySelector(".check-btn"), statusTxt = document.querySelector(".status-text"); //storing all captcha characters in array let allCharacters = ['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]; function getCaptcha()< for (let i = 0; i < 6; i++) < //getting 6 random characters from the array let randomCharacter = allCharacters[Math.floor(Math.random() * allCharacters.length)]; captcha.innerText += ` $`; //passing 6 random characters inside captcha innerText > > getCaptcha(); //calling getCaptcha when the page open //calling getCaptcha & removeContent on the reload btn click reloadBtn.addEventListener("click", ()=>< removeContent(); getCaptcha(); >); checkBtn.addEventListener("click", e =>< e.preventDefault(); //preventing button from it's default behaviour statusTxt.style.display = "block"; //adding space after each character of user entered values because I've added spaces while generating captcha let inputVal = inputField.value.split('').join(' '); if(inputVal == captcha.innerText)< //if captcha matched statusTxt.style.color = "#4db2ec"; statusTxt.innerText = "Nice! You don't appear to be a robot."; setTimeout(()=>< //calling removeContent & getCaptcha after 2 seconds removeContent(); getCaptcha(); >, 2000); >else < statusTxt.style.color = "#ff0000"; statusTxt.innerText = "Captcha not matched. Please try again!"; >>); function removeContent()
That’s all, now you’ve successfully created a Custom Captcha in HTML CSS & JavaScript. So this is all for today.
Thanks! Also Read
6 Key Lesson’s to Learn From Rich Dad Poor Dad for Programmers. For more details please visit Code With Imam.
Create a CAPTCHA Validation Form Using HTML, CSS, and JavaScript

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.» 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 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 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 many tickets for reselling. CAPTCHAs 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.
If you want to have a look at a live version of this project, you can check out this demo.
HTML CAPTCHA Code
In this project, you will be adding CAPTCHA to an HTML form. Use the following code to add CAPTCHA in HTML:
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:
- : This element is used to display the heading of the CAPTCHA form.
- : This element is used to display the CAPTCHA text.
- — This element is used to create an input box to type the CAPTCHA.
- : This button submits the form and checks whether the CAPTCHA and the typed text are the same.
- : This button is used to refresh the CAPTCHA.
- : This element is used to display the output according to the entered text.
- : This is the parent element that contains all the other elements.
This HTML page 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;
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. You can also give an elegant look to the form container using the CSS box-shadow property.
JavaScript CAPTCHA Code
You can use JavaScript to add functionality to a webpage. Use the following code to add complete functionality to the CAPTCHA validation form:
// 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, open the HTML file and you’ll see the following output: