CustomValidationAttribute指定的方法不被调用

问题描述:

我使用System.ComponentModel.DataAnnotations.CustomValidationAttribute来验证我的POCO类之一,当我尝试单元测试时,它甚至没有调用验证方法。CustomValidationAttribute指定的方法不被调用

public class Foo 
{ 
    [Required] 
    public string SomethingRequired { get; set } 
    [CustomValidation(typeof(Foo), "ValidateBar")] 
    public int? Bar { get; set; } 
    public string Fark { get; set; } 

    public static ValidationResult ValidateBar(int? v, ValidationContext context) { 
    var foo = context.ObjectInstance as Foo; 
    if(!v.HasValue && String.IsNullOrWhiteSpace(foo.Fark)) { 
     return new ValidationResult("Either Bar or Fark must have something in them."); 
    } 
    return ValidationResult.Success; 
    } 
} 

但是当我尝试对其进行验证:

var foo = new Foo { 
    SomethingRequired = "okay" 
}; 
var validationContext = new ValidationContext(foo, null, null); 
var validationResults = new List<ValidationResult>(); 
bool isvalid = Validator.TryValidateObject(foo, validationContext, validationResults); 
Assert.IsFalse(isvalid); //FAIL!!! It's valid when it shouldn't be! 

它甚至从来没有步入自定义验证方法。是什么赋予了?

尝试使用带bool的重载,该bool指定是否应验证所有属性。对最后一个参数传递true。

public static bool TryValidateObject(
    Object instance, 
    ValidationContext validationContext, 
    ICollection<ValidationResult> validationResults, 
    bool validateAllProperties 
) 

如果您传递false或忽略validateAllProperties,则只会检查RequiredAttribute。 这是MSDN documentation

+0

就是这样。谢谢。 – 2012-04-15 20:41:12