Documentation

Plugins/Validation/Validator/addMethod

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Plugins/Validation/Validator

addMethod( name, method, [message] )

Add a custom 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
message (Optional)String, Function
The default message to display for this method. Can be a function created by jQuery.validator.format(value). When undefined, an already existing message is used (handy for localization), otherwise the field-specific messages have to be defined.


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]; 
}, jQuery.format("Please enter the correct value for {0} + {1}"));

NameType