Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CustomValidationAttribute specifed method not being called

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?

like image 982
Ben Lesh Avatar asked Apr 15 '12 19:04

Ben Lesh


1 Answers

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.

like image 95
Wouter de Kort Avatar answered Sep 21 '22 03:09

Wouter de Kort