Reputation: 10907
Is there a standard practice for localizing the JQuery Validation messages?
I've been able to hack something together by declaring my own ClassRules and referencing them instead of the default 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'm just looking to see if there is a better way.
Upvotes: 4
Views: 8185
Reputation: 102468
There are validation files available if you want:
https://github.com/jzaefferer/jquery-validation/tree/master/src/localization
Just get the ones you need and reference the .js
file(s) in your page.
<script type="text/javascript" src="localization/messages_XX.js"></script>
Upvotes: 2
Reputation: 5022
You could overwrite the messages
object in the validator
object.
$.validator.messages = {
required: '<%: Resources.Strings_ValidationMessages.SelectionRequired %>'
};
Or you could potentially 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.
Upvotes: 5