Skip to content

Instantly share code, notes, and snippets.

@namklabs
Created April 22, 2013 18:18
Show Gist options
  • Save namklabs/5437246 to your computer and use it in GitHub Desktop.
Save namklabs/5437246 to your computer and use it in GitHub Desktop.
simple JavaScript math-based CAPTCHA
// This script should be loaded or embedded after the form.
// There must be an element with an ID of "answer" and a form with an ID of "myform".
// Beginners: you can change what IDs the script looks for by replacing all instances of #answer or #myform
function set_question(){
operation = Math.floor( Math.random() * 2 ); // 1 or 0
constant1 = Math.floor( Math.random() * 11 ); // 0 through 10
constant2 = Math.floor( Math.random() * 11 ); // 0 through 10
if( operation == 1 ){
operation_symbol = "+";
answer = constant1 + constant2;
} else if( operation == 0 ){
operation_symbol = "–";
answer = constant1 - constant2;
}
$("#problem").remove();
$("#answer").before('<strong id="problem">' + constant1 + ' ' + operation_symbol + ' ' + constant2 + '<br></strong>');
};
set_question();
$("#myform").submit(function(){
if( $('#answer').attr('value') == answer){
return true;
} else {
alert('Verification answer incorrect. Please try again.');
$('#answer').focus().attr('value','');
set_question();
return false;
}
});
@namklabs
Copy link
Author

This CAPTCHA is only designed to guard against simple garden-variety spam bots and will not likely hold up against high-grade spam bots. No guarantees are made that this script will prevent automated form submission. I am testing it to see how it holds up. Kinda new to the spam-fighting game. Suggestions are welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment