Omar
Omar

Reputation: 40202

Why is IValidatableObject.Validate only called if property validation passes?

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.

Upvotes: 17

Views: 7932

Answers (1)

marcind
marcind

Reputation: 53183

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.

Upvotes: 23

Related Questions