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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With