Tôi đang sử dụng System.ComponentModel.DataAnnotations.CustomValidationAttribute để xác thực một trong các lớp POCO của tôi và khi tôi thử đơn vị kiểm tra nó, nó thậm chí không gọi phương thức xác thực.CustomValidationAttribute specifed method không được gọi là
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;
}
}
nhưng khi tôi cố gắng để xác nhận điều đó:
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!
Nó bước không bao giờ thậm chí vào phương pháp xác nhận tùy chỉnh. Đưa cái gì?
Chính xác là như vậy. Cảm ơn bạn. –