Protect your forms from spam with Google reCAPTCHA

cover
Photo credit: StaticForms

Form spam is a real problem and the more popular your web site the more form spam you are likely to get. StaticForms has supported using a "honeypot" field to help identify form spam, and this will weed out the simpler spam bots, but sometimes a more sophisticated solution is needed.

reCAPTCHA is a free service from Google which protects your forms against spam and other types of automated abuse. Google's reCAPTCHA provides two versions, a checkbox and an "invisible" version (which is actually a badge which can, optionally, be hidden). This article will focus on integrating the former in to your forms. A companion article covers the "invisible" option reCAPTCHA option.

img

First, we'll create a new form. For now, we'll create a basic contact form and style it with Bootstrap:

<form action="<<YOUR UNIQUE FORM ENDPOINT>>" method="POST" id="contact-form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="First name" required />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" placeholder="[email protected]" required />
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" required class="form-control"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<div class="bg-white text-center pt-4 pb-2 mb-2">
<button type="submit" class="btn btn-primary rounded-pill">Submit</button>
</div>
</form>

Next, we need to register for a Google reCAPTCHA account and add the website we want to protect. To do this, go to the reCAPTCHA Admin Console and add your site, making sure to select reCAPTCHA v2 and the I'm not a robot" checkbox.

img

Once you’ve done that, you’ll be redirected to a page showing your site key and secret key.

img

Replace your_site_key in the form code with the displayed site key.

Next, you'll need to create a form end-point. If you haven't already signed up for a free StaticForms account, this would be good time.

From the Dashboard, click the Create Form button. On the next page, give your form a name and click Create.

img

The form configuration page will appear.

First, copy the Form Endpoint and paste it in to the action attribute in your form.

img

Next, scroll down to the Spam Protection section and click the Enable reCAPTCHA toggle, then enter the secret key that you got when you registered your site with Google reCAPTCHA earlier. We'll leave the rest of the configuration for now, so click Save.

img

That's it! Your form should now look something like this... img

Every time it's submitted, StaticForms will check with Google and flag the submission as spam or not based on Google's response.