考虑我有这两个属性:
public class Test
{
[Required(ErrorMessage = "Please Enetr Age")]
public System.Int32 Age { get; set; }
[Required(ErrorMessage = "Choose an option")]
public System.Boolean IsOld { get; set; }
}
当用户为Age
输入例如15并为Yes
选择“IsOld
”时,我会返回更正Age
或IsOld
的异常。我已经使用了CustomValidation
,但因为我的验证必须是静态的,所以我无法访问其他属性。我如何通过DataAnnotation
?
答案 0 :(得分:7)
您可以向类本身添加数据注释(Custom Validator)。在验证属性的isValid方法中,您应该能够转换对象并测试需要满足的值。
示例:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// setup test object
Test t = new Test() { Age = 16, IsOld = true };
// store validation results
Collection<ValidationResult> validationResults = new Collection<ValidationResult>();
// run validation
if (Validator.TryValidateObject(t, new ValidationContext(t, null, null), validationResults, true))
{
// validation passed
Console.WriteLine("All items passed validation");
}
else
{
// validation failed
foreach (var item in validationResults)
{
Console.WriteLine(item.ErrorMessage);
}
}
Console.ReadKey(true);
}
}
[TestValidation(ErrorMessage = "Test object is not valid")]
public class Test
{
public int Age { get; set; }
public bool IsOld { get; set; }
}
public class TestValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
bool isValid = false;
Test testVal = value as Test;
if (testVal != null)
{
// conditional logic here
if ((testVal.Age >= 21 && testVal.IsOld) || (testVal.Age < 21 && !testVal.IsOld))
{
// condition passed
isValid = true;
}
}
return isValid;
}
}
}