Friday, August 24, 2012

jQuery – Captcha/Anti-Spam without PHP or Server-Side code

In some cases, you won’t have access to server-side code for your forms, and when you need to add a form submitting to an off-site domain you may need anti-spam for sanity’s sake.
Caution: in order to use this method, you need to require users to have JavaScript enabled. This is a risk, as about 2% of US users have it disabled.
Server-side validation is harder to bypass and I don’t recommend using this jQuery-only method if you have access to those better methods.
With that in mind, let’s get started!
This is our basic form shell. Notice that there is no action for the form to take.

<div id="MyForm">
<form method="POST" name="info-form">
    <input type="hidden" value="/form-sent" name="returnURL" />
    <label for="First Name">First Name: </label>
    <input type="text" name="First Name" maxlength="40" />
    <label for="Last Name">Last Name: </label>
    <input type="text" name="Last Name" maxlength="80" />
    <label>Enter the below number: </label>
    <input type="hidden" value="701469" id="verifyNumHidden" name="verifyNumHidden" />
    <input type="text" id="enterVerify" name="enterVerify" />
    <div id="verifyNum"></div>
    <input type="submit" value="Submit" name="save" class="cat_button" />
</form>
</div>
 
Then, we add a script that:
  1. Generates a random number
  2. When form is submitted, tests to see if the user’s input matches the generated number
  3. If they match, change the form’s Action to what it ought to be.
That last step is the key. It means that the form has no valid action until the script gives it one.

jQuery(document).ready(function(){ 
 function randomgen()
 {
    var rannumber='';
  for(ranNum=1; ranNum<=6; ranNum++){
   rannumber+=Math.floor(Math.random()*10).toString();
  }
  $('#verifyNum').html(rannumber);
  $('#verifyNumHidden').val(rannumber);
 }
 randomgen();
//Verification number generate code Ends here
  
//Validation Starts Here    
 $('#MyForm').submit(function() {
  if($('#enterVerify').val() == $('#verifyNumHidden').val() ) {
   $('form').attr('action', 'https://example.com/MyForm');
   return true;
  }
  else
  {
   alert("Please Enter Correct Verification Number");
   randomgen();
   $('#enterVerify').select();
   $('#enterVerify').focus();
   return false;
  }
 });
});

 
This works against spambots because most of them don’t have JavaScript enabled, and the only time the form has the correct action is if the verification number is input correctly.
This script can be validated server-side as well – just see if the #verifyNumHidden value matches up with the #enterVerify value.

1 comment: