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.


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.


<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="styles.css">
<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>
<span id="output"></span>
<script src="script.js"></script>

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.


@import url('');
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.innerHTML = "Correct!";
} else {
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.innerHTML = "Correct!";
} else {
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.


247 Responses

  1. generic cialis online Bai Cong smiled, Asked The evaluation is so high Gu Min turned his head cialis without a doctor prescription reddit and glanced at her, and said with a smile, Isn t it because you are afraid that you will never change your mind Is this a joke I cialis without a doctor prescription reddit believe these two people must understand

  2. The only available study on infliximab in breast milk found that levels were either not present or were too low to be detected in the single patient studied. clomid generic name In these conditions, the early receipt of embryos for future transfer can serve as a correct strategy for treating infertility in this category of patients.

  3. cialis online without However, the use of a next generation sequencing platform to genotype genomic DNA was not included in the above, and much of the data interpretation appears to have been done manually, without automated methodology

  4. There are no randomized clinical trial data in male breast cancer patients to guide treatment and follow up recommendations, so we extrapolate from guidelines developed for women with breast cancer and for men with other cancers to outline reasonable follow up care for male breast cancer survivors how to beat tamoxifen weight gain Abnormal liver function tests can be a common side effect of Seroquel

  5. When you first sign up to NetBet Casino, deposit £100 to have your money doubled and play with £200; on top of this, get 10 Free Spins to enjoy as a new customer. Receive secret deals: Get Daily Bonuses With the Netbet Casino Book of Bonus Promotion NetBet Casino has lots of great bonuses, free spins and ongoing promotions. Sadly it can’t be rainbows and sunshine. Here a few negatives to look at when revealing 100 % free spins because the an advantage render. Any of these negative aspects are applicable to incentive also provides or gambling enterprise websites generally but they are well worth mentioning still. Play with our very own incentive link to accessibility so it special bonus give to possess the fresh people. Fool around with your 20 free revolves no-deposit extra. When you want so you can unlock the newest free 200 revolves no-deposit, you need to very first create an account. During the RGEM, a free-to-play pool will be available to eligible customers at DraftKings, allowing them to test their knowledge of responsible gaming while the operator will provide the answers on its Safer Play Portal. *Do not transact to any non-authorized agents such as 7 11, SMJ or Tambunting. Please send us copy of your deposit remittance slip with the information about the amount remitted, student’s name, course, date and the name of the depository bank so we could check and credit payment to your student’s account. We are an independent directory and reviewer of online casinos, a casino forum, and guide to casino bonuses. About Filipino Wealth Inventive casinos add free spins in addition to deposit bonuses as an additional incentive to play. In the best online casinos, you will find from 20 to a couple of hundred free spins attached to the first, or several first deposits. The amount of free spins is usually fixed and does not depend on how much you deposit, in contrast to the cash bonus determined by the percentage of the deposit made.

  6. 问:麻将怎么打四川麻将怎么打。 伞塔牌麻婆豆腐调料50g 一袋 我们首先讨论日麻的和牌过程究竟是怎么样的,日麻的听牌过程我认为大致可以分为: 1. 判断做特殊型还是面子型 2. (由于我之后要讨论读牌技巧,特殊型是容易读出的, 一副牌,54张牌。 问:麻将规则暗合了什么规律? 摸牌后,将任意一张牌放置在桌上的行为称为出牌。须注意的是在日本麻将中,打出的牌须在自己面前、牌桌中央按6张一列整齐排列,以便其他玩家查看。与牌山(山)相对应,这些舍弃的牌所处的位置被称为河。在一局中,如果从配牌开始直到荒牌,某位玩家所打出的牌都是幺九牌,且均未被别家鸣牌过,则成立”荒牌满贯”役。 在报告发布环节,《2022中国冰雪产业发展研究报告》由亚洲数据集团常务副总裁张莉发布,报告中对2021-2022年度中国冰雪产业发展总体情况和2022年产业发展特点及趋势等方面进行了全面、科学、系统的分析,为中国冰雪产业的发展提供了参考与借鉴。  推荐理由:剧组历时5年时间,从调研、走访、收集资料到纪实拍摄,通过电影先驱的后代和专家学者的生动讲述,以及老电影画面修复、动画经典翻新等多种表现形式,全方位再现了卢燕、黄柳霜、李小龙、蔡楚生、黎民伟等粤籍电影人对电影事业的热衷、对爱国情怀和民族担当的坚守,是一部传承电影文化的光影回忆录。 Repeat your search with another keyword

  7. Брови, хотя бы слегка выделенные с помощью геля, выглядят более ухоженными и выразительными. Изюминка Геля для бровей и ресниц Fixateur для Вас: Идеально подобранная кисточка безупречно ” укладывает” даже самые непослушные брови, текстура надежно их фиксирует в течение целого дня. Какой бы из способов укладки вы бы ни выбрали, гель для фиксации бровей — это настоящая палочка-выручалочка для быстрого макияжа. В повседневной рутине он в считаные минуты сделает образ более выразительным, а брови — ухоженными и чёткими. Наносить небольшое количество геля на ресницы и или брови, чтобы сформировать нужные контуры. Можно использоваться как самостоятельное средство или в качестве основы для туши. от 173 миль «Аэрофлот Бонус» большой выбор декоративных продуктов для бровей; На этот номер телефона будет отправлено sms с кодом восстановления: темно-коричневый Так что если вам нужна помощь в выборе прозрачного или оттеночного геля для укладки бровей — этот материал для вас (воспользуйтесь содержанием для быстрого перехода к основной части рейтинга). Сыворотка стимулирует рост более длинных и густых ресниц, восстанавливая состояние бровей и ресниц. Эта сыворотка изготовлена из натуральных ингредиентов, и ее также можно наносить с макияжем. Вам нужно наносить эту сыворотку точно так же, как жидкую подводку для глаз. Если вам меньше 30, применяйте его один раз в день, а если вам больше 30 лет, используйте его два раза в день. Способ применения: Утром и вечером нанесите сыворотку по линии роста ресниц и вдоль волосков. Дайте немного времени высохнуть, если потом наносите тушь для ресниц.  После нанесения каждая из составных частей сыворотки проникает в структуру волоска, напитывает его витаминами, различными полезными веществами. Применение такого средства стимулирует укрепление и рост ресниц, они становятся красивыми, крепкими. Зачастую основными компонентами активаторов выступают: Недавно начала пользоваться сывороткой для роста ресниц и бровей. Результат отличный: брови стали гуще, заполнились “пробелы”, но использую чаще, чем 2 раза в неделю. Отличное средство, рекомендую.

  8. Best ones i’ve come across so far are Stila waterproof and Daniel Sandler waterproof eyeliner. The latter I find particularly works well on the waterline. Available in the 2 most popular eyeliner shades- black and brown. For best application, it’s recommended to shake the eyeliner before use. Another clever hack for the tip to never dry out is to store the eyeliner with the tip down to keep it moist. Powered by WordPress VIP Do you guys have any hacks for oily eyelids? Let us know in the comments below. I have experimented with quite a few eyeliners from then and therefore, decided to make a comparison post on some black liquid eyeliners I own. Hope you find this post on ‘best liquid eyeliners in India‘ helpful. Swirlster Says: The Body Shop Matte Clay concealer is made for blemish-prone skin and gives a high-coverage, matte finish. It is available for INR 845 at The Body Shop. Hold the gua sha with the curved side to your face and glide it gently but firmly in upward motions, all the way to the hairline. Repeat 3-5 times per area. Use daily. What do the statues of David, The Thinker, and PietГ  have in common? They’re all sculpted to perfection, of course. So…what if we told you that you could be you, too? Get the DEAYOKA Rose Quartz Gua Sha Tool (originally $20) for just $8 at Amazon! Please note, prices are accurate at the date of publication, August 16, 2022, but are subject to change. Gua sha is the latest and greatest skincare trend that dates back to ancient times. Rooted in traditional Chinese medicine (TCM), this age-old technique is having a decidedly modern moment, and enthusiasts regularly flood social media with both the practice and its stunning results. If you’re ready to take your men’s skincare routine to the next level, incorporating esthetic practices, such as gua sha facials, can help your skincare work better while enhancing your results.

  9. Several companies have also developed topical products for pets. These oils, balms and creams are designed to target the endocannabinoid system within the skin and alleviate symptoms of irritating skin conditions. They also contain other soothing ingredients, such as eucalyptus oil, shea butter, beeswax or grapeseed oil to name a few, which work together with CBD and exert their calming effects on your pet’s skin. Dr. Silver provides information that can help pet owners understand better the benefits and the potential risks of using medical marijuana for their pets who have serious medical problems. Dr. Silver describes medical research from the 1970s that found that dogs are more sensitive to the adverse effects of THC than any other species. Several companies have also developed topical products for pets. These oils, balms and creams are designed to target the endocannabinoid system within the skin and alleviate symptoms of irritating skin conditions. They also contain other soothing ingredients, such as eucalyptus oil, shea butter, beeswax or grapeseed oil to name a few, which work together with CBD and exert their calming effects on your pet’s skin. Got questions about The Oz Store, our Orléans or Centretown locations, online shopping, home delivery, or about our selection of high quality products? Use this super-handy contact form to let us know, and we’ll get back in touch ASAP. The Oz Store is committed to serving Orléans, Ottawa and communities with friendly service and great cannabis, THC & CBD goods. Got Weed Online Dispensary Canada Not sure about Why don’t you join our discord channel and find out why so many people love us! Click here to join The regulation of non-medical cannabis sales falls to individual provincial and territorial governments, and not the federal government. Each of these government bodies have their own laws that authorize cannabis retailers to sell to consumers within their respective jurisdiction, but do not permit sales of non-medical cannabis to consumers outside of their jurisdiction.

  10. Hello bro!Show more!..
    пансионат для престарелых
    “Дом престарелых” – это общепринятое название для социального учреждения, которое оказывает услуги по социальной защите и помощи престарелым людям. Если вы ищете информацию о конкретном доме престарелых в Ростове-на-Дону, можете уточнить местоположение и другую информацию.
    пансионат для престарелых

  11. สมัครรับเครดิตฟรี Website to try playing slots for every camp for free. No need to apply, no deposit required. All slots players can Free trial of all slot games Update the latest games 2023, try playing slots, PG SLOT and many other camps. There are more than 1,000 games to choose from, open 24 hours a day.

  12. the laughter of children playing in the backyard creates a joyful and lively scene groaner I know many children ask for a pony, but I wanted a bicycle with rockets strapped to it

  13. Join our community forum to discuss and share experiences with
    “Quick Fix Plus 6.3.” Join our community forum to discuss and share experiences
    with “Quick Fix Plus 6.3.”

Leave a Reply

Your email address will not be published. Required fields are marked *