CustomValidationAttribute specifed method not being called

别说谁变了你拦得住时间么 提交于 2019-12-18 17:14:44

问题


I'm using the System.ComponentModel.DataAnnotations.CustomValidationAttribute to validate one of my POCO classes and when I try to unit test it, it's not even calling the validation method.

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;
  }
}

but when I try to validate it:

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!

It never even steps into the custom validation method. What gives?


回答1:


Try using the overload that takes a bool that specifies if all properties should be validated. Pass true for the last parameter.

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

If you pass false or omit the validateAllProperties, only the RequiredAttribute will be checked. Here is the MSDN documentation.



来源:https://stackoverflow.com/questions/10165143/customvalidationattribute-specifed-method-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!