How to localize validation messages in jQuery Validation?

Is there a standard practice for localizing jQuery validation messages?

I was able to hack something together by declaring my own ClassRules and referring to them instead of the standard ones.

My code.

<input class="localized-required" id="myTextInput" name="myTextInput" type="text" value="" /> <script language="javascript" type="text/javascript"> jQuery(document).ready(function () { $.validator.addMethod("localized-required", $.validator.methods.required, '<%: Resources.Strings_ValidationMessages.SelectionRequired %>'); $.validator.addClassRules( { "localized-required": { "localized-required": true } }); jQuery("#myForm").validate(); }) </script> 

I am just looking to see if there is a better way.

+4
source share
2 answers

You can overwrite the messages object in the validator object.

 $.validator.messages = { required: '<%: Resources.Strings_ValidationMessages.SelectionRequired %>' }; 

Or you can use your own defaultMessage function.

 $.validator.prototype.defaultMessage = function(element, method) { var locale = magicFunctionToGetLocale(); var message = $.validator.localizedMessages[locale][method]; return this.findDefined( this.customMessage( element.name, method ), this.customMetaMessage( element, method ), // title is never undefined, so handle empty string as undefined !this.settings.ignoreTitle && element.title || undefined, message, "<strong>Warning: No message defined for " + element.name + "</strong>" ); }; 

In the above example, $.validator.localizedMessages is an object created elsewhere in your code. The standard validation plugin does not have a localizedMessages object.

+5
source

Validation files are available if you want:

https://github.com/jzaefferer/jquery-validation/tree/master/src/localization

Just get the ones you need and link to the .js file on your page.

 <script type="text/javascript" src="localization/messages_XX.js"></script> 
+2
source

All Articles