views:

32

answers:

1

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.

+1  A: 

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.

CalebD
Thanks. The first suggestion is short and sweet I like it.
Justin