我正在创建一个自定义属性验证,它应该在抛出ValidationException时使用指定资源文件中的错误字符串。我是否正确地假设如果我抛出异常并且未在参数中指定错误字符串,它应该使用我在构造函数中指定的ErrorMessageResourceName和ErrorMessageResourceType?
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace OurProduct.Util
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniquenessAttribute : ValidationAttribute
{
public UniquenessAttribute()
{
ErrorMessageResourceName = "EmailUniqueError";
ErrorMessageResourceType = typeof (Resources.OurThing);
}
protected override ValidationResult IsValid(object value)
{
throw new ValidationException();
}
}
}
答案 0 :(得分:2)
如果OurThing
指向生成的强类型资源类,查找本地化字符串等,以下"EmailUniqueError"
是此类的静态属性之一,则以下内容应该有效:
public class UniquenessAttribute : ValidationAttribute
{
public UniquenessAttribute()
{
ErrorMessageResourceName = "EmailUniqueError";
ErrorMessageResourceType = typeof (Resources.OurThing);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (failure) // to implement
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
...
}
}
还要确保在进行测试时验证所有属性(例如,如果使用TryValidateObject,请确保将最后一个参数设置为true)。