Skip to main content

Bug Tracker

Side navigation

#3503 closed enhancement (fixed)

Opened October 21, 2008 09:54AM UTC

Closed October 21, 2008 06:16PM UTC

Last modified March 14, 2012 11:17PM UTC

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:
Description

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);
                    else
                        $.data(element.form, 'validator').settings.messages[element.name] = argument.messages;
                }
                /**** END PATCH ***/
				break;
			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(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), 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.

Attachments (0)
Change History (2)

Changed October 21, 2008 10:39AM UTC by joern comment:1

owner: → joern

Changed October 21, 2008 06:16PM UTC by joern comment:2

resolution: → fixed
status: newclosed

Fixed in [5897].