Making a simple math captcha using jquery

I wanted to write a simple Captcha that I could easily integrate into my own scripts that would work with or without Javascript. My first approach was to find open-source that I could pretty much just copy and paste into my code with little modification. All the cookie-cutter Captcha scripts I found were so bloated with extra code and were either only client-side (Javascript) or server-side (PHP), that I decided to create something from scratch. What I came up with is a script that uses Ajax for a smoother user experience (no browser reload on submit), but also works if the user has Javascript disabled for progressive enhancement (or graceful degradation).

Captcha Field
The following code section goes into your HTML form to create the Captcha section. To set the values of the fields to be added, use PHP rand() function to get a different random value each time the page is loaded (1st number is random number 1-4, and 2nd number is random number from 5-9 for easy use).

<input id="num1" class="sum" type="text" name="num1" value="<?php echo rand(1,4) ?>" readonly="readonly" /> +
<input id="num2" class="sum" type="text" name="num2" value="<?php echo rand(5,9) ?>" readonly="readonly" /> =
<input id="captcha" class="captcha" type="text" name="captcha" maxlength="2" />
<span id="spambot">(Are you human, or spambot?)</span>

Custom validation Mathod
Method basically gets the random values from the form, the total value entered by the user, adds them together and compares. If the two numbers don’t equal the total, then it returns an error. Otherwise it returns the result.
$.validator.addMethod('captcha',
function(value) {
$result = ( parseInt($('#num1').val()) + parseInt($('#num2').val()) == parseInt($('#captcha').val()) ) ;
$('#spambot').fadeOut('fast');
return $result;
},
'Incorrect value, please try again.'
);

Advertisements

3 thoughts on “Making a simple math captcha using jquery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s