Use the honeypot technique to filter spam form submissions

Updated

While most site developers use reCAPTCHA fields to block spam form submissions, reCAPTCHAs provide a suboptimal user experience when site visitors are filling out a form. Instead, you can use the honeypot technique which includes hidden form fields that bots fill out while real site visitors don’t. Then, you can set custom code to ensure the forms with fields filled out by bots are filtered out.

Create a hidden form field

To add and style your hidden form field:

  1. Add a div block to your form
  2. Give the div block a class name
  3. Ensure this class name doesn’t include words like “hidden”
  4. Add one or multiple input form fields to the div block
  5. Give the field(s) realistic names (to further fool the bot)
  6. Use either position, opacity, or display:none to hide the input field
    • You may need to experiment with these properties as some robots may be able to recognize and circumvent them. Additionally, the hidden input and structure may need to be updated over time as bots learn.

  7. Add a custom attribute of tabindex = "-1" to your hidden input
  8. Add a custom attribute to the hidden input label of aria-hidden = "true"
  9. Set element IDs with common names for the hidden input and the submit button

The custom attributes make sure users can’t tab to the input field and also ensure screenreaders won’t read the input’s label.

Use JavaScript to prevent form submission

Once your hidden form field is set up, you’ll need to add JavaScript to the page containing the form. This prevents the form being submitted if the hidden honeypot field is filled.

Here is an example script:

const submit = document.querySelector("#submit");
const honeypot = document.querySelector("#work-email");

honeypot.oninput = function () {
  if (honeypot.value.length > 0) {
    submit.disabled = true;
  }
};