How to provide localized validation messages for validation attributes(如何为验证属性提供本地化验证消息)
问题描述
我正在开发一个
IValidatioMetadaProvider 示例:
使用 Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;使用 System.ComponentModel.DataAnnotations;使用 System.Reflection;公共类 LocalizedValidationMetadataProvider : IValidationMetadataProvider{公共 LocalizedValidationMetadataProvider(){}公共无效 CreateValidationMetadata(ValidationMetadataProviderContext 上下文){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(newRequiredAttribute());foreach(上下文中的 var 属性.ValidationMetadata.ValidatorMetadata){var tAttr = 属性作为 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 = 名称;tAttr.ErrorMessage = null;}}}}}将提供程序添加到 Startup 类的 ConfigureServices 方法中:
services.AddMvc(options =>{options.ModelMetadataDetailsProviders.Add(new LocalizedValidationMetadataProvider());})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 Globalization and localization in ASP.NET Core, and it seems that it does not cover what I was looking for...
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.
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; }
}
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?
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.
- 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.
- 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.
- Add an implementation of IValidationMetadataProvider
- Add the localizations based on the Attributes Type Name like "RequiredAtrribute".
- Setup your app on the Startup file.
Sample ValidationsMessages.es.resx
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;
}
}
}
}
}
Add the provider to the ConfigureServices method on the Startup class:
services.AddMvc(options =>
{
options.ModelMetadataDetailsProviders.Add(new LocalizedValidationMetadataProvider());
})
这篇关于如何为验证属性提供本地化验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为验证属性提供本地化验证消息
基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
