【发布时间】:2022-01-04 19:38:25
【问题描述】:
我想在自定义属性中实现本地化,以检查该属性是否是有效的 IP 地址或主机名。到目前为止,验证工作正常,但我的问题是我只收到默认的英文错误消息,尽管我的本地已切换为德语。我正在处理资源文件。我不想为此实施客户端验证。我知道有办法实现适配器,但如果我错了,请纠正我,这仅用于客户端验证。
我的自定义验证类:
public class IPAddressOrHostnameAttribute : ValidationAttribute
{
public IPAddressOrHostnameAttribute(string propertyName, object desiredvalue, string errorMessage)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
ErrorMessage = errorMessage;
}
private string PropertyName { get; }
private object DesiredValue { get; }
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var instance = context.ObjectInstance;
var type = instance.GetType();
var propertyValue = type.GetProperty(PropertyName).GetValue(instance, null);
if (propertyValue.ToString() == DesiredValue.ToString() && value != null)
{
if (Regex.IsMatch(value.ToString(), AckConstants.VALIDIPADDRESSREGEX)
|| Regex.IsMatch(value.ToString(), AckConstants.VALIDHOSTNAMEREGEX))
{
return ValidationResult.Success;
}
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
我的模型类:
[Required(ErrorMessage = "The field {0} is required")]
[RegularExpression(@"^\S*$", ErrorMessage = "No white spaces allowed.")]
[IPAddressOrHostname(nameof(IsFileAdapter), true, "Please enter a valid IP address or hostname")]
[IPAddress(nameof(IsFileAdapter), false, "Please enter a valid IP address")]
[Display(Name = "Destination")]
public string Destination { get; set; }
我的启动类配置DataAnnotationLocalizerProvider:
services
.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResource)); // SharedResource is the class where the DataAnnotations (translations) will be stored.
})
本地化适用于默认属性,例如Required 等,但不适用于我的自定义验证属性。我不知道我的代码有什么问题。我已经阅读了 ASP.NET Core custom validation attribute localization 的 stackoverflow 帖子,但我不明白为什么我的本地化服务器端验证不起作用。希望有人可以帮助我或给我一个如何让它工作的例子,因为这个问题让我发疯。
【问题讨论】:
标签: asp.net-core custom-attributes asp.net-core-localization