2012-04-15 10 views
5

Sto usando System.ComponentModel.DataAnnotations.CustomValidationAttribute per convalidare una delle mie classi POCO e quando provo a testare l'unità, non viene nemmeno chiamato il metodo di convalida.CustomValidationAttributo metodo specificato non chiamato

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

ma quando provo a convalidarlo:

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! 

si passi mai, anche nel metodo di convalida personalizzato. Cosa dà?

risposta

7

Provare a utilizzare il sovraccarico che richiede un valore bool che specifica se tutte le proprietà devono essere convalidate. Passa true per l'ultimo parametro.

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

Se si passa false o omette le validateAllProperties, solo il RequiredAttribute sarà controllato. Ecco lo MSDN documentation.

+0

Era esattamente così. Grazie. –

Problemi correlati