Spam Prevention Using Hidden Form Fields

Not only do spambots struggle with recognizing required fields, but they also struggle with reading CSS or JavaScript, at least for now. The simplest solution, then, is to add a completely arbitrary field to each form and then to hide it using any number of such methods, for example:

<input type="text" name="foo" style="display: none;">

Alternatively, you could opt for something a little more complex like giving the field an ID or a class which would then force the bot to scan through your CSS files to determine the element’s visibility.

You could also use Javascript to remove the arbitrary field from display as the page loads, for example:

<div id="fooDiv">
<label for="foo">Leave this field blank</label>
<input type="text" name="foo" id="foo">
</div>
<script>
(function () {
    var e = document.getElementById("fooDiv");
    e.parentNode.removeChild(e);
})();
</script>

Notice how the field in the example has been given a label instructing the user to leave the field blank on the off chance they have JavaScript disabled.

Now you can rest assured that if the field ever has a value when the form submission reaches your server then the transaction can be discarded as junk. No matter which method you use the bot now has the added task of figuring out whether or not a given field is visible and/or required, which you could argue would take some pretty advanced AI or a more targeted approach on behalf of the spammer.

It might also help to randomize where the arbitrary field is displayed and how it is named so that it is even less predictable.

Of course, no solution is completely foolproof, as spam is sometimes still manually submitted by humans, so it never hurts to have more than one prevention procedure in place. To add another layer of protection, when spam is detected you should still go ahead and redirect the bot as though it were a successful form submission; I don’t like to give them any reason to probe.

I love good, old-fashioned, out of the box solutions, especially when they are elegant and work. I hope you find this trick as equally useful as I have, and I hope you’re willing to share any improvements or some other solutions you might happen to come up with.

Read the full article