Spam Control with jQuery
Recently at work I was faced with a problem. We use an outsourced CRM solution so I send lead forms directly to them. Things work but the only solution they have for spam control is using a captcha. A solution I’m not particularly fond of. Especially since one of those forms is in the footer of our site and it would just be flat out ugly.
I was already using the wonderful jQuery validation to validate form input so I wanted to find a way to tie it all together. Finally I came up with a way to essentially create a honeypot spam control using only jQuery. Please note that this method does require javascript to be active in a visitors browser for them to submit the form successfully. I don’t know anyone who surfs the web without javascript but supposedly they are out there.
Let’s say we have a form like the following that we want to add spam control to.
<form id="someform" action="formprocess.php" method="POST">
<label for="FirstName">FirstName</label><input id="FirstName" maxlength="40" name="FirstName" size="20" type="text" /><br>
<label for="LastName">LastName</label><input id="LastName" maxlength="40" name="LastName" size="20" type="text" /><br>
<label for="Email">Email</label><input id="Email" maxlength="40" name="Email" size="20" type="text" /><br>
<input type="submit" name="submit">
<script src="js/jquery.validate.js" type="text/javascript"></script>
It’s a very simple form but it will work to show how this works. First, what we need to do is add a field that all those spam bots simply can’t resist filling. In this example I’ll call the field “url” but you can call it whatever you want.
<input class="input url" id="url" placeholder="url" required>
Then in my CSS I’m going to hide this field for normal users with the following
.url {
display:none;
}
Regular users won’t even see this field and spambots it will be like trying to resist Scarlett Johansson. But we still need to do something when this hidden field is filled out and only submit it to users. Let’s add some JS.
<script>
$("#someform").validate(
{
submitHandler: function(form)
{
if($('input#url').val().length == 0)
{
form.submit();
}
}
});
What we’re doing there is adding to the validate function and checking to see if they “url” input has anything in it. If it’s blank we can assume it’s a real user and submit the form. We can take this one step further and adjust our script so the form doesn’t even have an action on it unless the above checks out. We can do that by removing the action portion from the first line of the form like so:
<form id="someform" method="POST">
Then we add a line to our script that adds the action if it’s not a spam bot.
$('form#someform').attr('action', 'formprocess.php');
That’s it. It won’t combat manually entered spam and there may be a few spam bots smart enough to get past it but in my experience it will reduce the spam you have to handle by 90% or more.
comments powered by Disqus