我有一个类的属性,我想将一些验证规则应用于。
我想创建一个自定义验证器: - 检查数字和/或地址是否存在 - 如果两者都不存在,则返回消息“这是必需的”
目前我有:
[CustomValidation(typeof(Course), "NumberOrAddressValidator")]
public class Information {
public string Number { get; set; }
public string Address { get; set; }
}
public static ValidationResult PhoneOrWebAddressRequiredValidator(string name, ValidationContext context)
{
if (Course.WebAddress == null)
{
return "Phone or web address is required";
}
else if(Course.PhoneNumber == null)
{
return "Phone or web address is required";
}
else
{
return ValidationResult.Success;
}
}
我是否正确地考虑过这个问题?我有点坚持理解“返回ValidationResult.Success”的确切做法。目前它在返回一个字符串(我想要返回的消息)时抛出错误。
任何提示和帮助都将不胜感激!
答案 0 :(得分:0)
根据我的理解,您应该使用Expressive-Annotation而不是进行自定义验证。通过在PMC中运行来安装NuGet包
PM> Install-Package ExpressiveAnnotations -Version 2.9.5
您的代码看起来像。
public class Information
{
[RequiredIf("Address==null", ErrorMessage = "Number or Address is Required")]
public string Number { get; set; }
[RequiredIf("Number==null", ErrorMessage = "Number or Address is Required")]
public string Address { get; set; }
}