Michael Trojanek (relativkreativ) — Bootstrapper and creator of things

This article was published on February 10th 2014 and takes about 2 minutes to read.

Use it with caution — it is probably still valid, but it has not been updated for over a year.

Spam-free forms

Every form on your website is an invitation for automated bots to spam you, create fake accounts or cause other harm. Let me show you one way to curtail this.

The key is differentiation between automated and real submissions without bothering real people:

Instead try to filter out illegal submissions without your users noticing.

We'll exploit the fact that an average bot crawls your website's HTML source instead of browsing content like normal users — most bots do not even evaluate JavaScript and CSS. Nonetheless we will avoid a script-based approach because lots of people disable JavaScript in their browsers for various reasons.

Imagine a simple signup form:

<form …>
  <input type="text" name="name" />
  <input type="text" name="email_address" />
  <input type="password" name="password" />
  <input type="submit" value="Sign up" />
</form>

Bots tend to fill out every input field, so we insert additional fields with ambiguous names:

<form …>
  <input type="text" name="name" />
  <input type="text" name="username" />
  <input type="text" name="email_address" />
  <input type="text" name="email" />
  <input type="password" name="passphrase" />
  <input type="password" name="password" />
  <input type="submit" value="Sign up" />
</form>

It is impossible to tell which fields need to be filled in and which ones need to be left blank by looking at the page's source. For real people, we hide the fields which must not be filled in using a simple CSS rule:

input[name=username],
input[name=passphrase],
input[name=email] {
  display: hidden;
}

Now, when the form is submitted, check the values of username, passphrase and email. If at least one of them is set, you can bet that the form was not submitted by a real person — he or she would have needed to disable or alter the page's CSS in order to see these input fields in the first place.

This will throw off most bots. Of course, a bot tailored specifically to your website will have no problem filling out this form, so there is no 100% coverage. But this technique will cut down fake submissions by a large amount.

Expand your DevOps skills!

Join hundreds of Rails developers and operators on my email list and get my ebook Build Your Own Rails Server as a free welcome gift.

No spam — guaranteed. You can leave at any time.