Posts tagged with: localization

Localizing jQuery plugins

I’ve spent some time to figure out how to localize my jQuery plugins and I’ve just found out a way that works just fine. Disclaimer: I’m not 100% sure of how namespacing works in jQuery so this might not be the correct way.

I’m using the meta header accept-language to control which language to use. It allows me to select the language in my backend (using user settings or whatever) instead of just using the languages defined by the browser. An ASP.NET MVC3 header would look like this in the layout:

<meta name="accept-language" content="@System.Globalization.CultureInfo.CurrentCulture.Name" />

You should be able to do the same thing in PHP or whatever language you use.

Next thing to do is to add the localization structure to your plugin script file:

(function($) {
    //globals
    $.yourPluginName = {
        texts: {
            title: 'Please wait, loading..'
        },
        translations: []
    };
    
    var methods = {
		// your methods here.
	};

    $.fn.yourPluginName = function(method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.yourPluginName');
        }

    };

})(jQuery);

That will make the plugin work if no languages are loaded. The translations will be loaded into the $.yourPluginName.translations array by another script.

We got one thing left to do before we can use the texts in your script. We need to load the correct language. Create another script called jquery.yourpluginnamne.localization.js and load it after$.yourPluginName.texts.anyTextName in your plugin to use the localized strings.


Simplified localization for DataAnnotations

Update

I’ve come up with a better localization method for MVC3. Read about it here.

Original article

The built in localization support in DataAnnotations is a bit hard to work with. You are supposed to do add the ResourceManager to each attribute that you add. The code is looking like something like this:

    public class User
    {
        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        public int Id { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        public string LastName { get; set; }
    }

You should of course move the strings to a static class or something like that.

The problem is that you have just added translation for the validation messages and not the actual model. There are actually no built in solutions for that problem.. If you google, you find some solutions using a custom LocalizedDisplayNameAttribute that uses the same approach as the DataAnnotationAttribute’s: Pointing on a resource type in the attribute constructor.

Updated source code for this solution:

    public class User
    {
        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_Id", NameResourceType=typeof(ModelTranslations))]
        public int Id { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_FirstName", NameResourceType=typeof(ModelTranslations))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_LastName", NameResourceType=typeof(ModelTranslations))]
        public string LastName { get; set; }
    }

Not very readable, is it? As you can see, I use the pattern ClassName_PropertyName for all strings definitions. It’s a safe way to avoid a name collision. The same word might not mean the same thing in different models.

The solution

What we need is a way to provide strings to all attributes WITHOUT specifying the resource in the attribute constructors. In this way we can easily move resources without having to change each attribute. Changing every attribute is not very DRY is it?

My solution is to create a singleton class that you can fetch strings from. Want a more flexible solution? Check my ShureValidation library (shameless advertising) that I’ve posted about earlier in this blog.

End result for the model:

    public class User
    {
        [Required]
        [LocalizedDisplayNameAttribute("User_Id")]
        public int Id { get; set; }

        [Required]
        [StringLength(40)]
        [LocalizedDisplayNameAttribute("User_FirstName")]
        public string FirstName { get; set; }

        [Required]
        [StringLength(40)]
        [LocalizedDisplayNameAttribute("User_LastName")]
        public string LastName { get; set; }
    }

A bit more readable? oooooh yes *uhu*.

Classes making it possible:

You have to derive all standard DataAnnotation attribute classes like this:

    public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
    {
        private string _displayName;

        public RequiredAttribute() 
        {
            ErrorMessageResourceName = "Validation_Required";
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            _displayName = validationContext.DisplayName;
            return base.IsValid(value, validationContext);
        }

        public override string FormatErrorMessage(string name)
        {
            var msg = LanguageService.Instance.Translate(ErrorMessageResourceName);
            return string.Format(msg, _displayName);
        }
    }

Next step is to add a custom DisplayName class:

    public class LocalizedDisplayNameAttribute : DisplayNameAttribute
    {
        private PropertyInfo _nameProperty;
        private Type _resourceType;

        public LocalizedDisplayNameAttribute(string className, string propertyName)
            : base(className + (propertyName == null ? "_Class" : ("_" + propertyName)))
        {

        }

        public override string DisplayName
        {
            get
            {
                return LanguageService.Instance.Translate(base.DisplayName) ?? "**" + base.DisplayName + "**";
            }
        }
    }

And finally create the language service:

    public class LanguageService
    {
        private static LanguageService _instance = new LanguageService();
        private List<ResourceManager> _resourceManagers = new List<ResourceManager>();

        private LanguageService()
        {
        }

        public static LanguageService Instance { get { return _instance; } }

        public void Add(ResourceManager mgr)
        {
            _resourceManagers.Add(mgr);
        }

        public string Translate(string key)
        {
            foreach (var item in _resourceManagers)
            {
                var value = item.GetString(key);
                if (value != null)
                    return value;
            }

            return null;
        }
    }

You can easily switch to a database or something like that if you need to.

Update

A follow up entry showing how to fix client-side validation in MVC3 can be found here.