Custom Cross validation in MVC 3+


So I think anyone reading this article has already figured out how to do regular Data Annotation for properties in your view model to handle things like Required, Regular Expressions (for validation on things like email and phone number), DisplayName, StringLength etc…

So the next question is, what if your business logic requires custom validation? Well there are many ways to do it and I have done it a few ways, but on a recent project I have found a cleaner way to place it all in one place in the View Model. A very basic way you might be doing this is creating a method in your View Model that handles the validation and if error doing a model.AddModelError(string key, string errorMessage). Now while nice, not very pretty and is kind of injecting errors into an object which just feels dirty.

Another way to do validation (and is now my preferred way) is to inherit from IValidator in you view model and overriding the validate method. Now, how does one do such a thing? here comes the code…


 public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)         {             if (someObject && someOtherObject == null)             {                 yield return new ValidationResult("Both of these fields cannot be left blank");             }

To me this makes things much cleaner and more importantly, more understandable for another developer. For those of you that do not know, yield will hold off on returning a value until the method is complete. In other words, if you had 3 more check statements all containing a yield return, ALL of the statements would finish before returning the list of results. This is apposed to using just return, which would return immediately on the first error it comes across. This creates a bad user experience because there may be more errors and upon next submission, the user will just get a new list of errors when they could have gotten them all at once in the first place.


I hope this helps others in the future.

Happy coding! Smile


About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in .NET, ASP.NET, C#, Classes, DataAnnotation, Generics, Interfaces, MVC, Namespaces, Validation and tagged , , , , , , , . Bookmark the permalink.

1 Response to Custom Cross validation in MVC 3+

  1. Pingback: MVC ModelState.AddError versus ModelStateDictonary | Object Reference Hell

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s