17

In my model, it seems that Validate() is only called AFTER both properties pass validation.

public class MyModel : IValidatableObject 
{
    [Required]
    public string Name { get; set;}

    [Required]
    public string Nicknames {get; set;}

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Nicknames != null && Nicknames.Split(Environment.NewLine.ToCharArray()).Count() < 2)
            return yield result new ValidationResult("Enter at least two nicknames, new [] { "Nicknames" });
    }
}

When a user enters a single line of text in the Nicknames text area but leaves the Name text box empty, only the Required error message for the Name property is displayed. The error message that should be displayed from the Validate() function never shows up.

Only after entering a name in the Name text box and some text in the Nicknames text is the Validate() function called.

Is this how it's supposed to work? It seems odd that a user is shown an error message on a subsequent page when the error is being caused on the current page.

Omar
  • 39,496
  • 45
  • 145
  • 213

1 Answers1

22

This is by design. Object-level validation does not fire until all the properties pass validation because otherwise it is possible that the object is incomplete. The Validate method is meant for thing like comparing one property to another. In your case you should write a custom property validator.

marcind
  • 52,944
  • 13
  • 125
  • 111
  • 2
    if the validate method contained the results of the property validation, we could check this for ourselves. i.e. void IValidatableObject.Validate(List result,ValidationContext validationContext) – Anthony Johnston Jan 26 '11 at 09:43
  • @AnthonyJohnston: That's true, but requiring developers to check it would mean that they might easily forget to check it, leading to null reference exceptions in cases where the framework well knows that the model isn't valid. I think this is a case of helping devs "fall into the pit of success" for common cases, and only requiring slightly more work in the rare cases where they want to provide even more information after the model has already been deemed invalid. – StriplingWarrior Nov 20 '15 at 17:42