Open In App

How to Add CAPTCHA to a Preexisting Contact Form using JavaScript?

Last Updated : 14 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To add CAPTCHA functionality to a preexisting contact form using JavaScript, you can create a simple text-based CAPTCHA or use a third-party service like Google reCAPTCHA. Here is how you can add a basic text-based CAPTCHA manually using JavaScript:

Example: Adding a Simple Text-Based CAPTCHA

Step 1: HTML Structure for the Contact Form

HTML
<form id="contactForm">
  <label for="name">Name:</label><br>
  <input type="text" id="name" name="name" required><br>
  <label for="email">Email:</label><br>
  <input type="email" id="email" name="email" required><br>
  
  <!-- CAPTCHA -->
  <div id="captchaContainer">
    <span id="captcha"></span>
    <button type="button" id="refreshCaptcha">Refresh CAPTCHA</button>
  </div>
  <label for="captchaInput">Enter CAPTCHA:</label><br>
  <input type="text" id="captchaInput" required><br>

  <button type="submit">Submit</button>
</form>

<div id="message"></div>

<script>
  // Generate random CAPTCHA
  function generateCaptcha() {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let captcha = '';
    for (let i = 0; i < 6; i++) {
      captcha += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return captcha;
  }

  // Display CAPTCHA
  function displayCaptcha() {
    const captchaText = generateCaptcha();
    document.getElementById('captcha').textContent = captchaText;
    return captchaText;
  }

  // Store the generated CAPTCHA
  let currentCaptcha = displayCaptcha();

  // Refresh CAPTCHA
  document.getElementById('refreshCaptcha').addEventListener('click', function() {
    currentCaptcha = displayCaptcha();
  });

  // Form submission
  document.getElementById('contactForm').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent default form submission
    const userInput = document.getElementById('captchaInput').value;

    if (userInput === currentCaptcha) {
      document.getElementById('message').textContent = 'CAPTCHA validated successfully. Form submitted!';
      // You can proceed with form submission here (e.g., send form data)
    } else {
      document.getElementById('message').textContent = 'Incorrect CAPTCHA. Please try again.';
    }
  });
</script>

Output:

Screenshot-2024-11-14-151134
Output

Explanation:

  1. HTML Elements:
    • A div to display the CAPTCHA and a button to refresh it.
    • An input field to allow users to enter the CAPTCHA value.
  2. CAPTCHA Generation Function:
    • generateCaptcha() generates a random string of 6 alphanumeric characters.
    • displayCaptcha() sets the CAPTCHA text in the appropriate <span>.
  3. CAPTCHA Validation:
    • When the form is submitted, it checks if the inputted CAPTCHA value matches the displayed CAPTCHA.
    • If it matches, the form can be processed; otherwise, an error message is shown.
  4. Refresh Button:
    • Allows the user to generate a new CAPTCHA if needed.

Additional Security Considerations:

  • Preventing Automated Form Submissions: While this simple CAPTCHA adds some protection, sophisticated bots may bypass it. Consider using a more robust solution like Google reCAPTCHA if security is critical.
  • Accessibility: Make sure to consider users with visual impairments. Providing an alternative audio CAPTCHA or ensuring compatibility with screen readers can be important.

Using Google reCAPTCHA (Alternative)

To integrate Google reCAPTCHA, follow these steps:

1. Sign Up for Google reCAPTCHA and obtain site and secret keys.

2. Include the reCAPTCHA Script in your HTML:

HTML
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

3. Add the reCAPTCHA Widget to your form:

HTML
<div class="g-recaptcha" data-sitekey="your-site-key"></div>

4. Verify reCAPTCHA on the Server Side after form submission by sending a POST request to Google's reCAPTCHA API for validation.

This provides more robust protection and is widely used for preventing spam and automated submissions


Next Article

Similar Reads