on Jan 5th, 2010Extending jQuery validation plugin – custom validation
JQuery validation plugin has saved me hours of development time on projects. It contains definitions for most validation tasks that you would need, including AJAX based validations. But if you have to do anything more than the ordinary, you have extend the library yourself. Here’s an example of an extension I wrote :
Functionality : I want to capture the twitter handle of a user on a form. Most users will enthusiastically enter the entire URL like http://twitter.com/itsmeritesh, some will leave out the http:// and enter the rest. I wanted to validate that the username was a single word, didn’t contain parts of a URL (mainly slashes) and didn’t mind it being empty.
// HTML Code // <form name="myform"> // <input type="text" id="twitterUrl"> <label for="twitterUrl" /> function isEmpty(Val) { if(Val.length==0) return true; for(var i=0; i< Val.length; i++) { if( " \t\n".indexOf( Val.charAt(i)) == -1 ) return false; } return true; } jQuery.validator.addMethod("handleOnly", function(value) { if(isEmpty(value)) return true; if ((value.split(" ").length == 1) && (value.search('/')==-1)) return true; else return false; }, "Please specify only one word"); $(document).ready(function(){ $("#myform").validate({ rules: { twitterUrl : { handleOnly: true } } messages: { twitterUrl: { handleOnly : "Only your twitter handle " } } }); });
handleOnly is a new extension written by using the jQuery.validator.addMethod() method. The rule then specifies whether the return from the function must be true or false, in my case its true. The message is displayed when the condition is not met by the value.

