Posted By

racl101 on 04/18/11

Statistics

Viewed 980 times
Favorited by 0 user(s)

Simple Math Captcha-like verification JavaScript script that uses jQuery (form) validation plugin

/ Published in: JavaScript

Don't forget to include jQuery validation plugin before this snippet. You can find it here:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Copy this code and paste it in your HTML
`jQuery(document).ready(function() {		var send_email_form = jQuery("form#my-form");	var lowerBound = 1;	var upperBound = 10;	// to generate random numbers between a range that starts somewhere other than	// zero use this formula where m is the lowest possible integer value of the range	// and n equals the top number of the range.	// Math.floor(Math.random() * (n - m + 1)) + m 	// generate random numbers between lowerBound and upperBound (inclusive)	var a = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;	var b = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound; 	jQuery("label#arithmetic_expression").html(a + " + " + b + " = ");	jQuery("input#eqtn_soln").val(a+b);	 	var validation_rules = {		name: "required",		email: {		 	required: true,		 	email: true		 },		subject: "required",		message: "required",		sum: {			required: true,			equalTo: "input#eqtn_soln"		}	}; 	var validation_messages = {		name: "please enter your name",		email: {		 	required: "Please enter your email address",			 	email: "Please enter a valid email address"						 },		subject: "please enter a message subject",		message: "please enter the message",		sum: {			required: "please answer the equation",			equalTo: "please answer the equation correctly"		}						};	 	//form validation with Javascript 	send_email_form.validate({		rules: validation_rules,		messages: validation_messages,		//errorClass: "form-error-style",		errorPlacement: function(error, element){			// places the error message after the element one line break below			error.insertAfter(jQuery("<br />").insertAfter(element));		}			});		});`