JavaScript Captcha – CodingNepal https://www.codingnepalweb.com CodingNepal is a blog dedicated to providing valuable and informative content about web development technologies such as HTML, CSS, JavaScript, and PHP. Thu, 11 May 2023 08:26:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Custom Captcha Generator in HTML CSS & JavaScript https://www.codingnepalweb.com/captcha-generator-html-css-javascript/ https://www.codingnepalweb.com/captcha-generator-html-css-javascript/#respond Tue, 09 May 2023 13:00:12 +0000 https://www.codingnepalweb.com/?p=5111 Captcha Generator in HTML CSS & JavaScript

CAPTCHA is an anti-bot security feature that combines distorted letters and numbers. It is employed to differentiate between humans and automated bots. Its purpose is to restrict access to specific online features like registration or comment posting. The distorted characters pose a challenge that bots have difficulty solving.

Creating a captcha generator using HTML, CSS, and JavaScript could be quite an important skill for a developer. Whether you’re building a personal website or developing a client’s site.

The purpose of this blog post is to teach you how to develop a Captcha Generator using HTML, CSS, and JavaScript. Essentially, we’ll be designing a form that randomly generates a combination of letters and numbers in an unordered format. We’ll then need to fill in the correct letters to determine if we’ve accurately solved the captcha. By the end of this post, you’ll have gained the knowledge and skills needed to create and implement captchas on your own websites.

Video Tutorial of Custom Captcha Generator in HTML

Steps For Creating Custom Captcha Generator in HTML

To create a captcha generator using HTML, CSS, and vanilla JavaScript, follow the given steps line by line:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js

To start, add the following HTML codes to your index.html file to create a basic layout for the captcha generator.

<!DOCTYPE html>
<!-- YouTube - CodingLab -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Captcha Generator</title>
    <link rel="stylesheet" href="style.css" />
    <!-- Fontawesome CDN Link -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
  </head>
  <body>
    <div class="container">
      <header>Captcha Generator</header>
      <div class="input_field captch_box">
        <input type="text" value="" disabled />
        <button class="refresh_button">
          <i class="fa-solid fa-rotate-right"></i>
        </button>
      </div>
      <div class="input_field captch_input">
        <input type="text" placeholder="Enter captcha" />
      </div>
      <div class="message">Entered captcha is correct</div>
      <div class="input_field button disabled">
        <button>Submit Captcha</button>
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

Next, add the following CSS codes to your style.css file to style the captcha generator and make it interactive and beautiful.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #826afb;
}
.container {
  position: relative;
  max-width: 300px;
  width: 100%;
  border-radius: 12px;
  padding: 15px 25px 25px;
  background: #fff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
header {
  color: #333;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
}
.input_field {
  position: relative;
  height: 45px;
  margin-top: 15px;
  width: 100%;
}
.refresh_button {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
  background: #826afb;
  height: 30px;
  width: 30px;
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
}
.refresh_button:active {
  transform: translateY(-50%) scale(0.98);
}
.input_field input,
.button button {
  height: 100%;
  width: 100%;
  outline: none;
  border: none;
  border-radius: 8px;
}
.input_field input {
  padding: 0 15px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}
.captch_box input {
  color: #6b6b6b;
  font-size: 22px;
  pointer-events: none;
}
.captch_input input:focus {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);
}
.message {
  font-size: 14px;
  margin: 14px 0;
  color: #826afb;
  display: none;
}
.message.active {
  display: block;
}
.button button {
  background: #826afb;
  color: #fff;
  cursor: pointer;
  user-select: none;
}
.button button:active {
  transform: scale(0.99);
}
.button.disabled {
  opacity: 0.6;
  pointer-events: none;
}

Finally, add the following JavaScript code to your script.js file to make the to generate random captcha and validated our entered captcha.

// Selecting necessary DOM elements
const captchaTextBox = document.querySelector(".captch_box input");
const refreshButton = document.querySelector(".refresh_button");
const captchaInputBox = document.querySelector(".captch_input input");
const message = document.querySelector(".message");
const submitButton = document.querySelector(".button");

// Variable to store generated captcha
let captchaText = null;

// Function to generate captcha
const generateCaptcha = () => {
  const randomString = Math.random().toString(36).substring(2, 7);
  const randomStringArray = randomString.split("");
  const changeString = randomStringArray.map((char) => (Math.random() > 0.5 ? char.toUpperCase() : char));
  captchaText = changeString.join("   ");
  captchaTextBox.value = captchaText;
  console.log(captchaText);
};

const refreshBtnClick = () => {
  generateCaptcha();
  captchaInputBox.value = "";
  captchaKeyUpValidate();
};

const captchaKeyUpValidate = () => {
  //Toggle submit button disable class based on captcha input field.
  submitButton.classList.toggle("disabled", !captchaInputBox.value);

  if (!captchaInputBox.value) message.classList.remove("active");
};

// Function to validate the entered captcha
const submitBtnClick = () => {
  captchaText = captchaText
    .split("")
    .filter((char) => char !== " ")
    .join("");
  message.classList.add("active");
  // Check if the entered captcha text is correct or not
  if (captchaInputBox.value === captchaText) {
    message.innerText = "Entered captcha is correct";
    message.style.color = "#826afb";
  } else {
    message.innerText = "Entered captcha is not correct";
    message.style.color = "#FF2525";
  }
};

// Add event listeners for the refresh button, captchaInputBox, submit button
refreshButton.addEventListener("click", refreshBtnClick);
captchaInputBox.addEventListener("keyup", captchaKeyUpValidate);
submitButton.addEventListener("click", submitBtnClick);

// Generate a captcha when the page loads
generateCaptcha();

Conclusion and Final Words

I hope this blog post taught you how to make your own Captcha Generator using HTML, CSS, and JavaScript. The coding process is simple and easy to understand, so you can customize your generator to your needs.

With this skill, you can make your website more secure and prevent spam or hacking. I’m confident that this post gave you the tools and confidence to create a great Captcha Generator. I recommend you to check my blog on Strong Password Generator in HTML CSS & JavaScript. This will also help you to enhance you JavaScript skills.

If you face any difficulties while creating your own captcha generator or your code is not working as expected, you can download the source code files for this captcha generator for free by clicking on the download button, and you can also view a live demo of this card slider by clicking on the view live button.

View Live Demo

 

]]>
https://www.codingnepalweb.com/captcha-generator-html-css-javascript/feed/ 0
Create Custom Captcha in HTML CSS & JavaScript https://www.codingnepalweb.com/create-custom-captcha-in-javascript/ https://www.codingnepalweb.com/create-custom-captcha-in-javascript/#comments Sun, 25 Jul 2021 10:07:04 +0000 https://www.codingnepalweb.com/?p=2188 Create Custom Captcha using 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], as you can see in the preview image, 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.

Video Tutorial of Create Custom Captcha in JavaScript

 
In the video, you have seen the demo of this custom captcha and the codes behind creating this captcha. I have already told you that I used HTML CSS & JavaScript. With the help of JavaScript, I generated random 6 characters and check these with the user value.

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 or download 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.

You might like this:

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. You can also download the source code files of this Captcha program from the given download button.

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. So download code files to use images also.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Custom Captcha in JavaScript | CodingNepal</title>
  <link rel="stylesheet" href="style.css">
  <!-- Font Awesome CDN Link for Icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
  <div class="wrapper">
    <header>Captcha in JavaScript</header>
    <div class="captcha-area">
      <div class="captcha-img">
        <img src="captcha-bg.png" alt="Captch Background">
        <span class="captcha"></span>
      </div>
      <button class="reload-btn"><i class="fas fa-redo-alt"></i></button>
    </div>
    <form action="#" class="input-area">
      <input type="text" placeholder="Enter captcha" maxlength="6" spellcheck="false" required>
      <button class="check-btn">Check</button>
    </form>
    <div class="status-text"></div>
  </div>
  <script src="script.js"></script>
</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* Import Google font - Poppins & Noto */
@import url('https://fonts.googleapis.com/css2?family=Noto+Serif:ital@1&family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
::selection{
  color: #fff;
  background: #4db2ec;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #4db2ec;
}
.wrapper{
  max-width: 485px;
  width: 100%;
  background: #fff;
  padding: 22px 30px 40px;
  border-radius: 10px;
  box-shadow: 8px 8px 8px rgba(0, 0, 0, 0.05);
}

.wrapper header{
  color: #4db2ec;
  font-size: 33px;
  font-weight: 500;
  text-align: center;
}
.wrapper .captcha-area{
  display: flex;
  height: 65px;
  margin: 30px 0 20px;
  align-items: center;
  justify-content: space-between;
}
.captcha-area .captcha-img{
  height: 100%;
  width: 345px;
  user-select: none;
  background: #000;
  border-radius: 5px;
  position: relative;
}
.captcha-img img{
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 5px;
  opacity: 0.95;
}
.captcha-img .captcha{
  position: absolute;
  left: 50%;
  top: 50%;
  width: 100%;
  color: #fff;
  font-size: 35px;
  text-align: center;
  letter-spacing: 10px;
  transform: translate(-50%, -50%);
  text-shadow: 0px 0px 2px #b1b1b1;
  font-family: 'Noto Serif', serif;
}
.wrapper button{
  outline: none;
  border: none;
  color: #fff;
  cursor: pointer;
  background: #4db2ec;
  border-radius: 5px;
  transition: all 0.3s ease;
}
.wrapper button:hover{
  background: #2fa5e9;
}
.captcha-area .reload-btn{
  width: 75px;
  height: 100%;
  font-size: 25px;
}
.captcha-area .reload-btn i{
  transition: transform 0.3s ease;
}
.captcha-area .reload-btn:hover i{
  transform: rotate(15deg);
}
.wrapper .input-area{
  height: 60px;
  width: 100%;
  position: relative;
}
.input-area input{
  width: 100%;
  height: 100%;
  outline: none;
  padding-left: 20px;
  font-size: 20px;
  border-radius: 5px;
  border: 1px solid #bfbfbf;
}
.input-area input:is(:focus, :valid){
  padding-left: 19px;
  border: 2px solid #4db2ec;
}
.input-area input::placeholder{
  color: #bfbfbf;
}
.input-area .check-btn{
  position: absolute;
  right: 7px;
  top: 50%;
  font-size: 17px;
  height: 45px;
  padding: 0 20px;
  opacity: 0;
  pointer-events: none;
  transform: translateY(-50%);
}
.input-area input:valid + .check-btn{
  opacity: 1;
  pointer-events: auto;
}
.wrapper .status-text{
  display: none;
  font-size: 18px;
  text-align: center;
  margin: 20px 0 -5px;
}

@media (max-width: 506px){
  body{
    padding: 0 10px;
  }
  .wrapper{
    padding: 22px 25px 35px;
  }
  .wrapper header{
    font-size: 25px;
  }
  .wrapper .captcha-area{
    height: 60px;
  }
  .captcha-area .captcha{
    font-size: 28px;
    letter-spacing: 5px;
  }
  .captcha-area .reload-btn{
    width: 60px;
    margin-left: 5px;
    font-size: 20px;
  }
  .wrapper .input-area{
    height: 55px;
  }
  .input-area .check-btn{
    height: 40px;
  }
  .wrapper .status-text{
    font-size: 15px;
  }
  .captcha-area .captcha-img{
    width: 250px;
  }
}

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 += ` ${randomCharacter}`; //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(){
 inputField.value = "";
 captcha.innerText = "";
 statusTxt.style.display = "none";
}

That’s all, now you’ve successfully created a Custom Captcha in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any error/problem, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/create-custom-captcha-in-javascript/feed/ 9