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:
- Add a div block to your form
- Give the div block a class name
- Ensure this class name doesn’t include words like “hidden”
- Add one or multiple input form fields to the div block
- Give the field(s) realistic names (to further fool the bot)
- Use either position, opacity, or display:none to hide the input field
- Add a custom attribute of tabindex = "-1" to your hidden input
- Add a custom attribute to the hidden input label of aria-hidden = "true"
- 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;
}
};