Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Validation message internationalization

For example, I would like this default ASP.NET MVC 4 validation message: The value 'qsdqsdqs' is not valid for Montant to be displayed in french.

I found this package http://nuget.org/packages/Microsoft.AspNet.Mvc.fr/ and installed it but how do I get it to work ?

I added <globalization culture="fr-FR" uiCulture="auto:fr" /> to web.config and referenced the dll but the message is still in english

like image 496
Catalin DICU Avatar asked Feb 05 '13 14:02

Catalin DICU


1 Answers

First of all you should keep your messages in Resources files like that:

Resources/ErrorMessages.resx // default messages
Resources/ErrorMessages.fr.resx // for french 

On server side it's vary easy, and you can do it by adding an attribute to your model. Do it like that:

[Required(ErrorMessageResourceType = typeof(Resources.ErrorMessages), ErrorMessageResourceName = "FieldRequired")]

where "FieldRequired" is one of the fields in Resources.ErrorMessages

The tricky part is when you want the client side validation to work as well. Than you have to create your own attribute class which extends one of the attributes and also implements IClientValidatable.

You to it like that:

public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
    {
        public override string FormatErrorMessage(string name)
        {
            return String.Format(ErrorMessages.FieldRequired, name);
        } 

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRequiredRule(String.Format(ErrorMessages.FieldRequired, metadata.DisplayName));
            return new[] { rule };
        }
    }

From now on you use CustomRequired instead of Required in your models. You also don't have to specify the message each time.

EDIT

Now I've seen your comment on SynerCoder's answer - that you don't want to translate messages yourself. Well I don't think it's the right approach. Even if you find something that will translate the standard messages for you it won't translate any custom messages, so you'll probably end up mixing 2 approaches. This usually leads to magic errors you don't know how to bite. I strongly suggest you do the translations yourself (it's not much to do - something like 20 or so?). The benefit will be a flexible solution with no unexpected errors.

like image 154
Andrzej Gis Avatar answered Nov 15 '22 09:11

Andrzej Gis