jQuery: The Write Less, Do More JavaScript Library

Plugins/Validation/Validator/addMethod

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Plugins/Validation/Validator

addMethod( name, method, message )

Add a new validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.
Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx
Arguments:

nameString
The name of the method, used to identify and referencing it, must be a valid javascript identifier
methodCallback
The actual method implementation, returning true if an element is valid
messageString, Function
The default message to display for this method. Can be a function created by String.format(value).


Examples:

Add a validation method that checks if a value starts with a certain domain.

jQuery.validator.addMethod("domain", function(value, element) { 
  return this.optional(element) || /^http://mycorporatedomain.com/.test(value); 
}, "Please specify the correct domain for your documents");

Adds a validation method that checks if a given value equals the addition of the two parameters.

jQuery.validator.addMethod("math", function(value, element, params) { 
 return this.optional(element) || value == params[0] + params[1]; 
}, String.format("Please enter the correct value for {0} + {1}"));

NameType