Custom Captcha Security in JavaScript

Custom Captcha Security in JavaScript
Code Snippet:New way to Captcha
Author: Alok Kumar Singh
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 641
License: MIT
Edit Code online: View on CodePen
Read More

This code implements a custom Captcha security system in JavaScript. It generates a grid of random numbers and marks a subset of them for the user to identify. This Captcha helps verify user interactions on websites.

You can use this code on your website’s forms to enhance security. It helps prevent automated bots from submitting forms by requiring users to solve the Captcha puzzle. This improves your website’s security and ensures that real users are interacting with your content.

How to Create Custom Captcha Security in JavaScript

1. Start by creating an HTML form on your webpage where you want to implement the Captcha. You can copy and paste the following HTML code. This code includes the form, Captcha container, and input field.

<form action="#" method="POST" class="main-form" id="mainForm">
    <h1 id="resultCapcha"></h1>  
    <svg class="patternDrow" height="250" width="250" id="patternDrowPolyline"></svg>  
    <div class="captcha-container" id="captchaContainer">
      <!-- Captcha Items go here -->
      
    </div>
    <div class="input-group">
      <label for="captchaInput">Insert the marked numbers in order <br/> (starting from top left)</label>
      <input type="text" autocomplete="off" id="captchaInput">
    </div>
    <input type="submit" value="Submit" class="btn submit-btn">
  </form>

2. The CSS code included in the snippet ensures that your Captcha looks visually appealing and fits well with your website’s design. Feel free to customize the styles to match your site’s theme.

@import url('https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;600&display=swap');

*, *::before, *::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Rubik', sans-serif;
}

html {
  font-size: 10px;
}

body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.captcha-wrong
{
color: red;
}
.captcha-success
{
color: rgb(5, 201, 15);
}
.marked{
  background-color: royalblue !important;
}
.patternDrow{
  position: absolute;
  z-index: 100;  
  margin-left: 5%;
  text-align: center;
}
.main-form {
  background: #fff;
  width: 40rem;
  padding: 3rem 2rem;
  box-shadow: 0 0 1rem .1rem rgba(0, 0, 0, 0.1);
  border-radius: .5rem;
}

.captcha-container {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(3, 8rem);
  grid-auto-rows: 8rem;
  grid-gap: .5rem;
  margin-bottom: 2rem;
}

.captcha-item {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgb(237, 237, 237);
  font-size: 3rem;
  font-weight: 500;
  position: relative;
}

.marked::before {
  content: "✔";
  position: absolute;
  top: .5rem;
  right: .5rem;
  font-size: 2rem;
}

label[for="captchaInput"] {
  font-size: 1.6rem;
  font-weight: 500;
}

#captchaInput {
  display: block;
  width: 100%;
  padding: .8rem 1rem;
  margin-top: 1rem;
  border: .1rem solid rgba(0, 0, 0, .3);
  border-radius: .5rem;
   box-sizing: border-box;
}

.submit-btn {
  margin-top: 2rem;
  padding: .8rem 2rem;
  color: white;
  background-color: black;
  border: none;
  border-radius: .5rem;
  outline: none;
  font-size: 1.6rem;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

3. Finally, add the following JavaScript code to your project. This code generates a dynamic Captcha with random numbers and highlights specific numbers for user identification. It also verifies user input against the generated Captcha.

const captchaContainer = document.querySelector("#captchaContainer");
const captchaInput = document.querySelector("#captchaInput");
const mainForm = document.querySelector("#mainForm");
const resultCapcha = document.querySelector("#resultCapcha");
const patternDrowPolyline = document.querySelector("#patternDrowPolyline");
const gridCount = 9;

let result = "";

const createCaptcha = () => {
  var points = "";
  var markCount = 0;
  var captchaItemList = []; 

  for (let i = 0; i < gridCount; i++) {
    var captchaItem = document.createElement("div");
    captchaItem.classList.add("captcha-item");
    // captchaItem.id = `captcha-item-${i}`;

    const randNum = Math.random().toString(20).substr(2, 1);
    
    captchaContainer.appendChild(captchaItem);
    captchaItem.innerHTML = randNum;
  }
    
  const captchaItemId = document.getElementsByClassName("captcha-item");


    while(markCount < 5){
        let selectCaptchaItem = Math.floor(Math.random() * 8);
        
        if(captchaItemList.includes(selectCaptchaItem) == false){
            captchaItemList.push(selectCaptchaItem);
            captchaItemId[selectCaptchaItem].classList.add("marked");
            markCount++;
        }
    }

    captchaItemList.sort();

    captchaItemList.forEach(element => {
        switch (element) {
            case 0:
            points += "40,40,";
            break;
            case 1:
            points += "125,40,";
            break;
            case 2:
            points += "210,40,";
            break;
            case 3:
            points += "40,120,";
            break;
            case 4:
            points += "125,120,";
            break;
            case 5:
            points += "210,120,";
            break;
            case 6:
            points += "40,210,";
            break;
            case 7:
            points += "125,210,";
            break;
            case 8:
            points += "210,210,";
            break;
        }

        result += captchaItemId[element].innerHTML;    
    });
    patternDrowPolyline.innerHTML = ("<polyline points='" + points + "' style='fill:none;stroke:rgb(38, 216, 2);stroke-width:3' />");
    console.log(captchaItemList);
      

    // }
  // alert(points);
//   patternDrowPolyline.innerHTML = ("<polyline points='" + points + "' style='fill:none;stroke:rgb(38, 216, 2);stroke-width:3' />");
};

createCaptcha();

captchaInput.addEventListener("input", () => {
  // alert('val'+captchaInput.value );
  // alert('res'+result );
  if (captchaInput.value != result) {
    captchaInput.classList.add("wrong-captcha");
    resultCapcha.innerHTML = "Wrong Captcha";
    resultCapcha.classList.add("captcha-wrong");
    resultCapcha.classList.remove("captcha-success");
  } else {
    captchaInput.classList.remove("wrong-captcha");
    resultCapcha.classList.remove("captcha-wrong");
    resultCapcha.classList.add("captcha-success");
    resultCapcha.innerHTML = "Captcha Verified";
  }
});

// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("submit");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
var message = document.getElementById("message");

btn.onclick = function() {
  if (captchaInput.value != result) {
    modal.style.display = "block";
    message.innerHTML = "Wrong Captcha!! Try again"
    message.style.color = "red";
  } else {
    modal.style.display = "block";
    message.innerHTML = "Captcha Varified"
    message.style.color = "green";
  }
}

span.onclick = function() {
  modal.style.display = "none";
}

// mainForm.addEventListener("submit", (e) => {
//   if (
//     captchaInput.classList.contains("wrong-captcha") ||
//     (!captchaInput.value.length && result.length)
//   ) {
//     e.preventDefault();
//   }
// });

That’s all! hopefully, you have successfully created a custom Captcha Security in JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X