开发者

MVC3 localization for default validation errors

When I put [Required] attribute on my ViewModel's property MVC3 automatically generate error messages like: The Price field is required.

My site's single language is Russian, so I want to have localized error messages. I can localize field's name with [Display(Name = "blablabla")], but how can I localize the field is required part?

Update: I know, that I can change an error message for concrete field by sp开发者_如何学编程ecifying it [Required(ErrorMessage = "blablabla")], is there a way I can change it in one place for all [Required] attributes, so I could use just [Required] without additional parameters, and it took the localized error message from some ressource/config/etc?


I've created an alternative solution where you don't have to use the attributes for the localization. I've created custom model/validation meta data providers.

All you need to do is to download my code and do the following in your global.asax:

var stringProvider = new ResourceStringProvider(Resources.LocalizedStrings.ResourceManager);
ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(stringProvider);
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider(stringProvider));

(the ResourceStringProvider is my default implementation but it's easy to create an alternative that reads from XML files or a database)

You can read about it here: http://blog.gauffin.org/2011/09/easy-model-and-validation-localization-in-asp-net-mvc3/

I'm going to release a nuget package as soon as I'm finished with my view localization and my alternative HTML helpers.


The Required attribute has properties that allow the message to be read from a resource string. See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx for the details


Granted for this you should already have some Resource Manager which can return localized texts for string keys. My ResourceManager has static accessor for this (and registrations with Unity for DI), so there's no need to pass it. In the global.asax:

ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(); //field name localization
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider()); //validation message localization

And the implementation is this:

public class LocalizedModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
                                                    Func<object> modelAccessor, Type modelType, string propertyName)
    {

        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        if (containerType == null || propertyName == null)
            return metadata;

        if (metadata.DisplayName == null)
            metadata.DisplayName = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName);

        if (metadata.Watermark == null)
            metadata.Watermark = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "Watermark");

        if (metadata.Description == null)
            metadata.Description = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "Description");

        if (metadata.NullDisplayText == null)
            metadata.NullDisplayText = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "NullDisplayText");

        if (metadata.ShortDisplayName == null)
            metadata.ShortDisplayName = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "ShortDisplayName");

        return metadata;
    }
}

public class LocalizedModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {
        foreach (var attribute in attributes.OfType<ValidationAttribute>())
            attribute.ErrorMessage = ResourceManager.Current.GetValidationMessage(attribute);

        return base.GetValidators(metadata, context, attributes);
    }
}


Simply add/change the globalization tag in web.config:

<system.web>
  <globalization uiCulture="your culture"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜