MVC Validation message internationalization

前端 未结 2 1942
广开言路
广开言路 2021-01-19 02:57

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 f

2条回答
  •  轮回少年
    2021-01-19 03:52

    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 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.

提交回复
热议问题