CAPTCHA Generator Using JavaScript: Step by Step Guide.

0

In today's digital world, CAPTCHAs have become an essential tool for protecting websites from bots and spam. But have you ever wondered how CAPTCHAs are actually generated? Well, this blog will take you on a step-by-step journey to create your very own CAPTCHA generator using JavaScript.


captcha generator using javascript


You’ll learn in this blog post:

  • How to generate random numbers.
  • How to generate random alphanumeric values.
  • How to generate captcha with some random stylings characters.
  • Verify the captcha on click.


Javascript Functions, methods used:

  • Math.random() : For generating random values from 0 to 1. Including 0 but not 1. 
  • Math.floor() : Round the number down.
  • For loop : For running some block of code again and again till the limit setted.


Video Tutorial on CAPTCHA Generator:



CAPTCHA Generator.

We'll start by building a function that generates random strings of characters and numbers, giving you complete control over the length and complexity of your CAPTCHAs. Then, we'll explore different alignment options to make sure your CAPTCHAs look tidy or cluttered


But that's not all! We'll also implement a verification system to ensure that users are accurately entering the CAPTCHA. This extra layer of security will help protect your website from malicious bots.


And to make things even more convenient, we'll add a feature that allows users to generate a new CAPTCHA if they find the current one too difficult. This will give them a better chance of successfully completing the CAPTCHA and accessing your website.


File structure:

  1. Create one folder.
  2. Open it in your code editor.
  3. Create two files in that folder index.html and index.css.


I’ve integrated javascript within the html file inside the script tag. You can create a separate file and link it to an html file.


We are going to create a captcha generator with just 3 steps.


Step 1: Create design of captcha.

First lets create captcha generator design with html and css.


HTML


<!DOCTYPE html>
<html lang="en">
<!-- maketechstuff.com -->

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Captcha Generator | maketechstuff.com</title>
    <link rel="stylesheet" href="index.css">
</head>

<body>

    <div class="box">
        <div class="message"></div>

        <div class="captcha_box">
            <div class="captcha"></div>
            <button type="button" class="refresh_button" title="Refresh">&#8635</button>
        </div>

        <div class="input_box">
            <input type="text" placeholder="Enter Captcha" class="text">
        </div>
        <button type="button" class="submit">Verify</button>

    </div>

</body>

</html>


CSS


* {
    padding: 0px;
    margin: 0px;
    font-family: sans-serif;
}

body {
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #9575cd;
}

.box {
    width: 350px;
    background-color: #fff;
    border-radius: 5px;
    padding: 20px;
    text-align: center;
    box-shadow: 0px 5px 15px -12px #000;
}

.captcha_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px;
    background-color: #f9f9f9;
    border-radius: 5px;
}

.captcha {
    font-size: 30px;
    margin: 15px;
    display: flex;
    justify-content: center;
    pointer-events: none;
}
.captcha p{
    pointer-events: none;
}

.input_box {
    width: 100%;
    background-color: #fff;
    margin: 20px 0px;
    border: 2px solid #f2f2f2;
    border-radius: 5px;
}

input[type="text"]{
    width: 90%;
    background-color: #fff;
    padding: 10px 0px;
    font-size: 25px;
    border: none;
    outline: none;
}

button {
    font-size: 25px;
    font-weight: bold;
    padding: 10px 30px;
    border-radius: 5px;
    border: none;
    background-color: #9575cd;
    color: #fff;
    display: block;
    cursor: pointer;
    transition: 0.5s;
}

button:active {
    transform: scale(0.9);
}
.refresh_button{
    padding: 15px 20px;
}
.submit{
    width: 100%;
}
.message{
    font-size: 20px;
    font-weight: bold;
    margin: 20px 0px;
    display: none;
}

Output:


captcha generator design


So the design is ready. Now let's add functionality to generate alphanumeric values to show as a captcha using JavaScript.


Step 2: Create a function to generate captcha.

We are going to create a function to generate alpha numeric values to use as a captcha.


And call that function onclick of button and also call it on window load.


We’ll pick the values from stored or pre-declared alpha numeric values(1 to 9, a to z, A to Z values) from a variable, based on randomly generated value (as index) and stores in the html element in which we have to show the captcha (which is captcha class).


JavaScript



    let captcha = document.querySelector(".captcha");
    let refresh_button = document.querySelector(".refresh_button");
    let text = document.querySelector(".text");
    let submit = document.querySelector(".submit");
    let message = document.querySelector(".message");

    let string = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    let generated_value = "";

    window.addEventListener("load" , generate_captcha);
    refresh_button.addEventListener("click" , generate_captcha);

    let letters = "";
    function generate_captcha(){
        message.style.display = "none";

        generated_value = "";
        for (let i = 0; i < 5; i++) {
            generated_value += string[Math.floor(Math.random() * string.length)];
            captcha.innerHTML = generated_value;
            
        }

        // Adding styles to random characters of captcha to be in disalign position.
        

  

    }

Output:


Demo of captcha generator


So captcha is generated on click and on window load. You can generate more length captchas, by adjusting the for loop limit.


Now we want it to be in unalign manner. Means it should not be in a proper line. It should be up, down , small, big, etc. So let's make it that way.


So for that we are going to enclose each random value (alpha numeric value for captcha) in a p tag with a JavaScript map function.


JavaScript



    function generate_captcha(){
        message.style.display = "none";

        generated_value = "";
        for (let i = 0; i < 5; i++) {
            generated_value += string[Math.floor(Math.random() * string.length)];
            // captcha.innerHTML = generated_value;
            captcha.innerHTML = generated_value.split("").map((letter , index) => `<p>`+ letter +`</p>`).join("");
        }

        // Adding styles to random characters of captcha to be in disalign position.


    }


So now when you open the console it looks like this.


captcha generator


Now let's add styling to some random p tags so that it looks some cluttered. Like this.


JavaScript


    function generate_captcha(){
        message.style.display = "none";

        generated_value = "";
        for (let i = 0; i < 5; i++) {
            generated_value += string[Math.floor(Math.random() * string.length)];
            // captcha.innerHTML = generated_value;
            captcha.innerHTML = generated_value.split("").map((letter , index) => `<p>`+ letter +`</p>`).join("");
        }

        // Adding styles to random characters of captcha to be in disalign position.
        letters = document.querySelectorAll("p");

        let random_number1 = Math.floor(Math.random() * 5);
        let random_number2 = Math.floor(Math.random() * 5);
        let random_number3 = Math.floor(Math.random() * 5);

        letters[random_number1].style.margin = "0px 3px";
        letters[random_number1].style.rotate = "30deg";

        letters[random_number2].style.margin = "0px 4px";
        letters[random_number2].style.rotate = "-20deg";
        letters[random_number2].style.fontWeight = "bold";
        letters[random_number2].style.transform = "translateY(10px)";

        letters[random_number3].style.margin = "0px 4px";
        letters[random_number3].style.rotate = "35deg";
        letters[random_number3].style.transform = "translateY(-10px)";


    }



Output:


captcha generator demo


Now let's add verification functionality. Means checking if the user entered captcha is correct or not according to given or current generated captcha.


Step 3: Verifying captcha.

As each captcha characters are in separate html elements (p tag). So first we need to combine it, and then verify it.


Here we are going to verify simply with if condition by “===” . (Remember to verify it at the backend too. if you are working on backend).


And based on conditions status we are going to show a message.


JavaScript


    // Verify captcha.
    letters = document.querySelectorAll("p");

    submit.onclick = function(){
        let combined_letters = "";

        for (let c = 0; c < letters.length; c++) {
            const element = letters[c];
            combined_letters += element.innerText;
            
        }
        if(text.value === combined_letters){
            message.style.display = "block";
            message.style.color = "green";
            message.innerHTML = "Captcha verified";
        }else{
            message.style.display = "block";
            message.style.color = "red";
            message.innerHTML = "Please enter valid captcha";
        }
    }



You can see demo in above YouTube Video.


You may like:

  1. How to create a random passord generator using HTML CSS and JavaScript.
  2. How to generate a random alphanumeric values.
  3. How to generate a random numbericals value.
  4. How to generate a random OTP values using JavaScript.
  5. How to create OTP input fields using HTML CSS and JavaScript.


Final code:



So that's it, a random captcha generator is ready with verifying functionality. If you have any query or suggestion, feel free to leave a comment in the comment section.


Thanks for reading this far. 


Tags

Post a Comment

0Comments

Share your thoughts.

Post a Comment (0)
To Top