Bug Tracker

Opened 14 years ago

Closed 14 years ago

Last modified 10 years ago

#3503 closed enhancement (fixed)

Add custom messages in rules method

Reported by: lightglitch Owned by: joern
Priority: major Milestone: 1.3
Component: plugin Version: 1.2.6
Keywords: validate Cc:
Blocked by: Blocking:


This would be really nice to add custom messages in the rules function for dynamic rules like this:

$("#field").rules("add",  {"required":true,"range":[5,45],"messages":
{"required":"The field can\'t be blank.","range":"The field must have
5 to 45 characters."}}); 

So for this I have applied a patch to the rules function:

	rules: function(command, argument) {
		var element = this[0];
		if (command) {
			var staticRules = $.data(element.form, 'validator').settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
                /**** PATCH ***/
                if (argument.messages) {
                    if ($.data(element.form, 'validator').settings.messages[element.name])
                        $.extend($.data(element.form, 'validator').settings.messages[element.name],argument.messages);
                        $.data(element.form, 'validator').settings.messages[element.name] = argument.messages;
                /**** END PATCH ***/
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
                    /**** PATCH ***/
                    delete $.data(element.form, 'validator').settings.messages[element.name];
                    /**** END PATCH ***/
					return existingRules;
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
                    /**** PATCH ***/
                    delete $.data(element.form, 'validator').settings.messages[element.name][method];
                    /**** END PATCH ***/
				return filtered;
		var data = $.validator.normalizeRules(
		), element);
		// make sure required is at front
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		return data;

Hope it helps.

Change History (2)

comment:1 Changed 14 years ago by joern

Owner: set to joern

comment:2 Changed 14 years ago by joern

Resolution: fixed
Status: newclosed

Fixed in [5897].

Note: See TracTickets for help on using tickets.