Contact forms are a common target for automated spam submissions. Google reCAPTCHA helps protect your forms by verifying whether a visitor is a real user before allowing the form to be submitted.
This article shows how to integrate reCAPTCHA v3 into a standard HTML contact form.
Table of Contents
Before You Begin
Before implementing reCAPTCHA, you will need:
- A Google reCAPTCHA account
- A registered website in the reCAPTCHA dashboard
- A valid Site Key and Secret Key
The Site Key is used on your website, while the Secret Key is used to verify requests on the server side.
Step 1: Load the reCAPTCHA JavaScript Library
Add the following code inside the <head> section of your page:
<script src="https://www.google.com/recaptcha/api.js"></script> This script loads the resources required for reCAPTCHA to function.
Step 2: Add the Submission Callback
Add the following JavaScript code before the closing </body> tag or within the page header:
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script> This function is executed after reCAPTCHA validates the visitor and submits the form.
Step 3: Update the Submit Button
Add the following attributes to the button that submits the form:
<button
class="g-recaptcha"
data-sitekey="YOUR_SITE_KEY"
data-callback="onSubmit"
data-action="submit">
Submit
</button> Replace YOUR_SITE_KEY with the Site Key generated in your Google reCAPTCHA account.
How It Works
When a visitor clicks the button:
- reCAPTCHA analyzes the request in the background.
- A verification token is generated.
- The
onSubmit()function is executed. - The form is submitted only after reCAPTCHA validation is completed.
Unlike previous versions, reCAPTCHA v3 does not typically require users to solve image-based challenges. Instead, it evaluates visitor behavior and assigns a score that can be checked on the server side.
Important Security Consideration
Adding reCAPTCHA to the form protects the client side of the application, but it should not be the only protection mechanism.
For proper validation, the generated token should also be verified on the server using your reCAPTCHA Secret Key. This prevents attackers from bypassing the protection by sending requests directly to the form processing script.
Summary
Google reCAPTCHA v3 can help reduce automated spam submissions by validating visitors before a form is submitted. Integration requires loading the reCAPTCHA JavaScript library, adding a callback function, and updating the form’s submit button with the appropriate attributes. For maximum security, server-side token verification should also be implemented.