validation plugin

jQuery Validation Plugin – Add custom method

Posted on: November 2nd, 2012 by taff No Comments


During my daily use of jQuery I find that I always seem to use the same plugins over and over again. One of these is the jQuery validate Plugin. Out of the box it offers just about everything you need to validate forms prior to submitting them to a database or passing them to a further script for processing.

If however you want to validate a field in a form that requires something out of the usual you can create further methods using the following technique. In this example I'm going to validate to (almost) ensure that a German telephone number is valid. I saw almost because you can't really allow for all eventualities but this is my shot. In my opinion it's better to let the odd wrong phone number through than not allow a real number because it is out of scope.

$(document).ready(function() {
jQuery.validator.addMethod("fonNummer", function(value, element) {
return this.optional(element) || /^([0-9\s\(\)\+\-\/]{9,30})*$/.test(value);
}, "Gültige Telefonnummer?");

//Add the rule to a field with our new method
rules: {
field: {
required: true,
fonNummer: true


You can now use the fonNummer rule in the same way you would any of the built in rules. A great resource for finding regular expressions such as one for validating US phone numbers where you quite often add the extension as either x123 or ext123.

I also use the jQuery validator for simulating a multipage form (why load a new page when only the form changes?). The rules are simply added when the user clicks next (if everything validates). I will go into this in further depth some time in the future.