Devigner blog about development and design

Rails Captcha Validation With Javascript

A very simple way to keep machines out of your forms is through CAPTCHA’s. A very simple implementation of this in your Rails forms is by using a nifty little javascript. This is not the preferred method, since there are ways around the javascript, but it is definitely a nice little spam helper.
Note: This will not stop spiders, only human interaction with forms. This is only intended to show how to integrate jcap with a rails app. Not in anyway a tutorial on how to stop spiders


Set it up

1. Download the Jcap scripts from here. Decompress and copy them to your public/javascripts folder. In my case, I left the cimg folder within my javascripts folder.

2. Add the javascript include tags to your view (within the head).

<%= javascript_include_tag 'jcap', 'md5' %>

3. Add an onload event to the body tag.

<body onload="document.xfrm.uword.focus();">

4. Modify your form tags to resemble:

<%= form_tag({:action => 'create'}, {:onSubmit => 'return jcap()', :name => 'xfrm'}) %> <%= render :partial => 'addlistingform' %> <script language="javascript" type="text/javascript">cimg()</script> <noscript>[This resource requires a Javascript enabled browser.]</noscript> Please enter the code as it is displayed above. <input type=text name="uword" id="uword" value="" size=20> <%= submit_tag "Create" %> <%= end_form_tag %>

I modified my jcap.js file to reflect the location of my cimg folder. If you keep yours in the javascripts folder you will need to do so as well.

The developer of the Jcap scripts recommends you use some further steps to make sure your captcha is covered by requiring the verification form field.

This is a neat script but does not solve all problems. As I mentioned, if a browser does not have javascript enabled this will fail.