A very possible reason as to why your ASP.NET MVC ViewModel's IEnumerable Validate method is not firing

If you are dealing with an ASP.NET MVC project chances are that your ViewModels or POCO classes are implementing the Validate method of the IValidatableObject interface to validate on the server side the incoming data from the UI of your application. Chances are also that you are decorating the properties of these classes with validation attributes like [Required].

As stated here when you use both validation attributes and the Validate method, the property attributes are going to be applied first, if they pass the object attributes are checked and if they also pass the Validate method of the current class will run and validate the input.

However, what happens when you use no attributes in the property or object level and you only implement the Validate method? Why is the method not firing?

Lets say we have the following ViewModel which contains a more complex structure of properties that are of different object types:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class OrderViewModel : IValidatableObject
{
    public long Id { get; set; }

    public Customer Customer { get; set; }

    public Product Product { get; set; }

    public DateTime DateOrdered { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        // validation code for the OrderViewModel class
    }
}

and the POCO Customer class looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Customer : IValidatableObject
{
    public long Id { get; set; }

    public string Firstname { get; set; }

    public string Lastname { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        // validation code for the Customer class
    }
}

and let us suppose that the Product class has also a few properties which are validated inside a Validate method of the Product class.

In this scenario, starting from the OrderViewModel, the first validation will be made in the Customer object. If the Validate method of Customer returns validation errors, then the Validate method of the Product and more importantly of the OrderViewModel are not going to be fired, which is exactly the reason we were looking for.

I hope this will help someone out there :)

comments powered by Disqus