Login Form with Captcha using HTML, CSS, and JavaScript (Source Code)

Faraz

By Faraz -

Learn how to design a secure login form with Captcha using HTML, CSS, and JavaScript. Boost user authentication and security on your website.


Creating Login Form with Captcha using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

In today's digital age, online security is a paramount concern for website owners and users alike. One of the fundamental aspects of securing user data and ensuring a safe online experience is the implementation of a robust login system. An essential component of such a system is a well-designed login form that includes a Captcha.

This blog post aims to guide you through the process of creating a secure and user-friendly login form with Captcha, utilizing the power of HTML, CSS, and JavaScript. By following these steps, you can significantly enhance the security of your website, protect user accounts from unauthorized access, and provide a seamless and intuitive login experience. Let's dive in and explore how to create a login form that strikes the perfect balance between security and user satisfaction.

Source Code

Step 1 (HTML Code):

To create an effective login form, begin with designing the HTML structure. Here are the steps to follow:

  1. Create a <form> element to enclose the login components.
  2. Add <label> and <input> elements for the username and password fields.
  3. Include a submit <button> for the user to log in.
  4. Incorporate placeholders and IDs for accessibility.
  5. Structure your HTML in a clean and organized manner.

Let's break down the code step by step:

1. <!DOCTYPE html>: This is the document type declaration, and it tells the web browser that the document is an HTML5 document.

2. <html lang="en">: This is the opening tag of the HTML document. The lang attribute is set to "en," indicating that the content is in the English language.

3. <head>: This section contains metadata about the web page, and it's not displayed on the web page itself.

  • <title>Home</title>: Sets the title of the web page to "Home." This title typically appears in the browser's title bar or tab.
  • <meta charset="UTF-8" />: Specifies the character encoding of the document as UTF-8, which is a widely used character encoding for handling various character sets.
  • <meta name="viewport" content="width=device-width" />: This meta tag is often used for responsive web design. It configures the viewport to adapt to the device's width, making the page more mobile-friendly.
  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">: This line links an external CSS file (Font Awesome) to the web page. Font Awesome is a popular icon font library.
  • <link rel="stylesheet" href="styles.css" />: This line links another external CSS file called "styles.css" to the web page. This is a custom stylesheet for styling the web page.

4. <body>: This is the main content of the web page that is visible to the user.

5. <div class="login-form">: This div element defines a container with the class "login-form." It contains the entire login form.

6. <div class="form-title">: This is a container for the login form title. It contains the text "Login."

7. <div class="form-input">: This container seems to be used for each input field in the form. It contains a label and an input element.

  • <label for="username">Username</label>: This is a label for the username input field.
  • <input type="text" id="username">: This is an input field for entering a username. The id attribute is "username."
  • Similarly, there's a form input for the password.

8. <div class="captcha">: This is a container for a CAPTCHA input.

  • <label for="captcha-input">Enter Captcha</label>: This is a label for the CAPTCHA input.
  • Inside this container, there is a preview element, a CAPTCHA input field, and a button for refreshing the CAPTCHA.

9. <div class="form-input">: This is another form input container for the login button.

  • <button id="login-btn">Login</button>: This is a button element for submitting the login form with the ID "login-btn."

The following lines link JavaScript files for additional functionality:

  • <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>: This script tag links an external JavaScript library called "sweetalert." It's used for creating pop-up alerts or messages on the web page.
  • <script src="script.js"></script>: This script tag links an external JavaScript file called "script.js," which is a custom JavaScript file for enhancing the functionality of the web page.

Step 2 (CSS Code):

Utilize CSS to make your login form visually appealing and user-friendly:

  1. Apply CSS styles to elements like the form, labels, and input fields.
  2. Use responsive design to ensure compatibility across various devices.
  3. Consider color schemes, fonts, and spacing for a polished look.

Let's break down the code step by step:

1. The first block of code selects all elements with an asterisk (*) and applies the following CSS rules:

  • margin: 0px; sets the margin of all elements to zero pixels.
  • padding: 0px; sets the padding of all elements to zero pixels.
  • box-sizing: border-box; changes the box model for all elements, ensuring that padding and borders are included in the element's total width and height.

2. The code block for the body selector defines the styling for the webpage's body:

  • font-family: sans-serif; specifies the font family to be a generic sans-serif font.
  • background: #f5f5f5; sets the background color of the body to a light grayish color.

3. The .login-form selector defines the styling for a login form within the webpage:

  • position: absolute; positions the form absolutely within its containing element.
  • top: 50%; left: 50%; centers the form in both the vertical and horizontal directions.
  • transform: translate(-50%, -50%); fine-tunes the centering of the form by translating it up and to the left by 50%.
  • width: 90%; sets the form's width to 90% of its containing element.
  • max-width: 450px; sets a maximum width for the form to prevent it from becoming too wide.
  • background: #fff; gives the form a white background.
  • padding: 20px 30px; provides padding inside the form.
  • box-shadow and border properties create a shadow and border for the form, giving it a raised appearance.
  • border-radius: 10px; rounds the corners of the form.

4. The .login-form .form-title selector styles the form's title:

  • text-align: center; centers the text within the form.
  • font-size: 30px; sets the font size to 30 pixels.
  • font-weight: 600; makes the text bold.
  • margin: 20px 0px 30px; defines margins around the title.

5. The .login-form .form-input selector styles form inputs with some margin.

6. The .login-form .form-input label and .login-form .captcha label selectors style labels within the form:

  • display: block; makes the labels block-level elements.
  • font-size: 15px; sets the font size.
  • color: #111; sets the text color to a dark gray.
  • margin-bottom: 10px; adds space below the labels.

7. The .login-form .form-input input selector styles the input fields within the form:

  • width: 100%; makes the input fields take up the full width.
  • padding: 10px; provides padding inside the input fields.
  • outline: none; removes the default outline.
  • border-radius: 4px; rounds the input field corners.
  • border: 1px solid #888; gives the input fields a 1-pixel solid border with a gray color.

8. The .login-form .captcha selector adds some margin to the captcha section.

9. The .login-form .captcha .preview selector styles the captcha preview area:

  • Sets the color, width, height, line height, letter spacing, border, and font family.

10. The .login-form .captcha .captcha-form selector styles the captcha input and refresh button.

11. The #login-btn selector styles the login button:

  • Sets the margin, width, padding, background color, border radius, and color.
  • Adds a transition effect and cursor pointer on hover.

12. The #login-btn:hover selector changes the opacity of the login button on hover to create a visual feedback effect.

* {
  margin:0px;
  padding:0px;
  box-sizing:border-box;
}
body {
  font-family:sans-serif;
  background:#f5f5f5;
}
.login-form {
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  width:90%;
  max-width:450px;
  background:#fff;
  padding:20px 30px;
  box-shadow: rgba(17, 12, 46, 0.15) 0px 48px 100px 0px;
  border: 1px solid rgba(17, 12, 46, 0.15);
  border-radius: 10px;
}
.login-form .form-title {
  text-align:center;
  font-size:30px;
  font-weight:600;
  margin:20px 0px 30px;
  color:#111;
}
.login-form .form-input {
  margin:10px 0px;
}
.login-form .form-input label,
.login-form .captcha label {
  display:block;
  font-size:15px;
  color:#111;
  margin-bottom:10px;
}
.login-form .form-input input {
  width:100%;
  padding:10px;
  outline: none;
  border-radius: 4px;
  border:1px solid #888;
  font-size:15px;
}
.login-form .captcha {
  margin:15px 0px;
}
.login-form .captcha .preview {
  color:#555;
  width:100%;
  text-align:center;
  height:40px;
  line-height:40px;
  letter-spacing:8px;
  border:1px dashed #888;
  border-radius: 4px;
  font-family:"monospace";
}
.login-form .captcha .preview span {
  display:inline-block;
  user-select:none;
}
.login-form .captcha .captcha-form {
  display:flex;
}
.login-form .captcha .captcha-form input {
  width:100%;
  outline: none;
  padding:8px;
  border-radius: 4px;
  border:1px solid #888;
}
.login-form .captcha .captcha-form .captcha-refresh {
  width:40px;
  border:none;
  outline:none;
  background:#888;
  border-radius: 4px;
  color:#eee;
  cursor:pointer;
}
#login-btn {
  margin-top:5px;
  width:100%;
  padding:12px;
  border:none;
  outline:none;
  font-size:15px;
  text-transform:uppercase;
  background:#4c81ff;
  border-radius: 5px;
  color:#fff;
  transition: .3s;
  cursor:pointer;
}
#login-btn:hover{
  opacity: .8;
} 

Step 3 (JavaScript Code):

Use JavaScript to validate user input and provide real-time feedback:

  1. Write JavaScript functions to validate the username and password fields.
  2. Check for proper formatting, length, and the absence of malicious code.
  3. Display error messages or success indications in real-time.

Let me break down the code step by step:

1. The code is wrapped in an IIFE (Immediately Invoked Function Expression) to create a private scope, preventing global variable pollution.

2. An array called fonts is defined, containing four font styles: "cursive," "sans-serif," "serif," and "monospace."

3. A variable called captchaValue is declared and initialized to an empty string. This variable will store the current captcha value.

4. The code defines three functions:

a. generateCaptcha: This function generates a new captcha value. It does so by performing the following steps:

  • It generates a random number between 0 and 1 and multiplies it by 1,000,000,000.
  • It converts the resulting number to base64 using btoa.
  • It then truncates the base64 string to a length between 5 and 10 characters by using a random value.
  • The resulting string is stored in the captchaValue variable.

b. setCaptcha: This function creates the visual representation of the captcha and injects it into the HTML document. It generates an HTML string that includes each character of the captcha value. For each character:

  • It selects a random rotation angle between -20 and +10 degrees.
  • It selects a random font style from the fonts array.
  • It creates an HTML <span> element with the character, the chosen rotation angle, and font style.
  • These HTML elements are concatenated into a single string and set as the content of an element with the class "preview" inside an element with the class "captcha" within a form.

c. initCaptcha: This function initializes the captcha system by adding an event listener to a "captcha-refresh" button. When this button is clicked, it regenerates the captcha and updates the visual representation by calling generateCaptcha and setCaptcha. It also initially generates and sets the captcha when the page loads.

5. The initCaptcha function is invoked to set up the captcha system when the page loads.

6. The code adds an event listener to the "login" button. When the button is clicked, it checks if the value entered in the input field matches the current captchaValue. If the input matches, it displays a success message using a function called swal. If not, it displays an "Invalid captcha" message using the same swal function.

(function(){
  const fonts = ["cursive","sans-serif","serif","monospace"];
  let captchaValue = "";
  function generateCaptcha(){
    let value = btoa(Math.random()*1000000000);
    value = value.substr(0,5+Math.random()*5);
    captchaValue = value;
  }
  function setCaptcha(){
    let html = captchaValue.split("").map((char)=>{
      const rotate = -20 + Math.trunc(Math.random()*30);
      const font = Math.trunc(Math.random()*fonts.length);
      return `<span 
        style="
          transform:rotate(${rotate}deg);
          font-family:${fonts[font]}
        "
      >${char}</span>`;
    }).join("");
    document.querySelector(".login-form .captcha .preview").innerHTML = html;
  }
  function initCaptcha(){
    document.querySelector(".login-form .captcha .captcha-refresh").addEventListener("click",function(){
      generateCaptcha();
      setCaptcha();
    });
    generateCaptcha();
    setCaptcha();
  }
  initCaptcha();
  
  document.querySelector(".login-form #login-btn").addEventListener("click",function(){
    let inputCaptchaValue = document.querySelector(".login-form .captcha input").value;
    if(inputCaptchaValue === captchaValue){
      swal("", "Logging In!", "success");
    } else {
      swal("Invalid captcha");
    }
  });
})();

Final Output:

Creating Login Form with Captcha using HTML, CSS, and JavaScript.gif

Conclusion:

In conclusion, creating a robust and user-friendly login form with Captcha using HTML, CSS, and JavaScript is a crucial step in enhancing the security of your website. As cyber threats continue to evolve, safeguarding user data and accounts has never been more important.

By implementing the steps outlined in this guide, you can achieve the perfect balance between security and user experience. You'll not only protect your users from malicious actors but also provide a smooth and convenient login process.

Remember, a well-designed login form is a reflection of your commitment to user security and satisfaction. So, go ahead and implement these techniques to fortify your website's login system and keep your users safe.

Code by: Tilak

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post