Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 534
Omar Avatar asked Jan 22 '11 17:01

Omar


1 Answers

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.

like image 138
marcind Avatar answered Nov 15 '22 21:11

marcind