如何为验证属性提供本地化的验证消息 [英] How to provide localized validation messages for validation attributes

查看:107
本文介绍了如何为验证属性提供本地化的验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理ASP.NET Core应用程序,我想覆盖数据注释的默认验证错误消息,例如RequiredMinLengthMaxLength等.我在 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/本地化,而且似乎无法满足我的需求...

I am working on an ASP.NET Core application and I would like to override the default validation error messages for data-annotations, like Required, MinLength, MaxLength etc. I read the documentation at https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization and it seems that it does not cover what I was looking for...

例如,Required属性的验证错误消息对于任何模型属性始终可以相同.默认文本只是指出:必填{0}字段,从而{0}占位符将填充属性的显示名称.

For instance, a validation error message for the Required attribute can always be the same for any model property. The default text just states: The {0} field is required, whereby the {0} placeholder will be filled up with the property´s display name.

在我的视图模型中,我使用Required属性,而没有任何命名参数,例如...

In my view models, I use the Required attribute without any named arguments, like this...

class ViewModel
{
    [Required, MinLength(10)]
    public string RequiredProperty { get; set; }
}

我认为

设置ErrorMessageErrorMessageResourceName(和ErrorMessageResourceType)是不必要的开销.我以为我可以实现类似于IDisplayMetadataProvider的功能,以允许我在验证失败的情况下返回所应用属性的错误消息.这可能吗?

Setting an ErrorMessage or ErrorMessageResourceName (and ErrorMessageResourceType) is unnecessary overhead, in my opinion. I thought I could implement something similar to IDisplayMetadataProvider allowing me to return error messages for applied attributes, in case the validation has failed. Is this possible?

推荐答案

对于那些到此为止的人,为了寻找通用的解决方案,最好的解决方法是使用验证元数据提供程序.我的解决方案基于本文: AspNetCore MVC错误消息,我使用了.net框架样式本地化,并将其简化为使用设计的提供程序.

For those that end up here, in search of a general solution, the best way to solve it is using a Validation Metadata Provider. I based my solution on this article: AspNetCore MVC Error Message, I usted the .net framework style localization, and simplified it to use the designed provider.

  1. 将一个资源文件(例如 ValidationsMessages.resx )添加到您的项目中,并将访问修饰符"设置为内部"或公共",以便生成背后的代码,从而为您提供 ResourceManager 静态实例.
  2. 为每种语言 ValidationsMessages. es .resx 添加自定义本地化.请记住不要为此文件设置访问修饰符,代码是在步骤1上创建的.
  3. 添加 IValidationMetadataProvider
  4. 的实现
  5. 基于属性类型名称(例如"RequiredAtrribute")添加本地化.
  6. 在启动文件上设置您的应用.
  1. Add a Resource file for example ValidationsMessages.resx to your project, and set the Access Modifier as Internal or Public, so that the code behind is generated, that will provide you with the ResourceManager static instance.
  2. Add a custom localization for each language ValidationsMessages.es.resx. Remember NOT to set Access Modifier for this files, the code is created on step 1.
  3. Add an implementation of IValidationMetadataProvider
  4. Add the localizations based on the Attributes Type Name like "RequiredAtrribute".
  5. Setup your app on the Startup file.

示例验证消息. es .resx

Sample ValidationsMessages.es.resx

IValidatioMetadaProvider的示例:

Sample for IValidatioMetadaProvider:

using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

public class LocalizedValidationMetadataProvider : IValidationMetadataProvider
{
    public LocalizedValidationMetadataProvider()
    {
    }

    public void CreateValidationMetadata(ValidationMetadataProviderContext context)
    {
        if (context.Key.ModelType.GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(context.Key.ModelType.GetTypeInfo()) == null && context.ValidationMetadata.ValidatorMetadata.Where(m => m.GetType() == typeof(RequiredAttribute)).Count() == 0)
            context.ValidationMetadata.ValidatorMetadata.Add(new RequiredAttribute());
        foreach (var attribute in context.ValidationMetadata.ValidatorMetadata)
        {
            var tAttr = attribute as ValidationAttribute;
            if (tAttr?.ErrorMessage == null && tAttr?.ErrorMessageResourceName == null)
            {
                var name = tAttr.GetType().Name;
                if (Resources.ValidationsMessages.ResourceManager.GetString(name) != null)
                {
                    tAttr.ErrorMessageResourceType = typeof(Resources.ValidationsMessages);
                    tAttr.ErrorMessageResourceName = name;
                    tAttr.ErrorMessage = null;
                }
            }
        }
    }
}

将提供程序添加到Startup类的ConfigureServices方法中:

Add the provider to the ConfigureServices method on the Startup class:

services.AddMvc(options =>
{
     options.ModelMetadataDetailsProviders.Add(new LocalizedValidationMetadataProvider());
})

这篇关于如何为验证属性提供本地化的验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆