How to Add CAPTCHA to a Preexisting Contact Form using JavaScript?
Last Updated :
14 Nov, 2024
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:
OutputExplanation:
- 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.
- CAPTCHA Generation Function:
generateCaptcha()
generates a random string of 6 alphanumeric characters.displayCaptcha()
sets the CAPTCHA text in the appropriate <span>
.
- 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.
- 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
Similar Reads
Captcha Generator using HTML CSS and JavaScript A captcha is a way of verifying whether a user is human or not. A captcha is made up with the help of combining letters and digits. It ensures that the user attempting to access the platform is a human. So, without wasting time, let's get started.Application of CaptchaForm Authentication: For login
3 min read
How to clear form after submit in Javascript without using reset? Forms in JavaScript serve to gather specific user information, essential in various contexts like recruitment or inquiry submissions. While offline forms can be freely distributed, online forms must maintain a consistent structure for all users. After filling out a form, submission is crucial, but d
2 min read
How to Take Screenshot of a Div Using JavaScript? A screenshot of any element in JavaScript can be taken using the html2canvas library. This library can be downloaded from its official website. The below steps show the method to take a screenshot of a <div> element using JavaScript. ApproachIn this approach, we will create a blank HTML docume
2 min read
Create an QR Code Generator Project using HTML CSS & JavaScript Today, more than 75% of websites and apps use QR codes to share links, contact info, or event details quickly. Here, youâll learn how to make your own QR Code Generator using HTML, CSS, and JavaScript. Weâll guide you step by step, so even if youâre a beginner, you can follow along easily. By the en
3 min read
How to Prevent XSS Attacks in JavaScript? Cross-site scripting (XSS) is a security vulnerability that enables attackers to inject malicious scripts into web pages viewed by users, potentially leading to serious consequences such as data theft and unauthorized actions. Given that JavaScript is a fundamental technology in web development, it
4 min read