Server-Side Validation in MVC 3
This post is part of the series I’m doing on the newly released ASP.NET MVC 3.
In the first version of MVC there was very little support for validation. Most developers simply used jQuery validation on the client and implemented their own validation on the server. The release of MVC 2 came with several model validation improvements which have been enhanced even further with MVC 3.
How is it used
Let’s take a look at an example where validation helpers can be quite useful – user registration.
Here’s a snippet from the View.
Pretty straightforward. All the validation is made possible with attributes on the view model.
All of this is already possible with MVC 2. Let’s add validation to say that Password and ConfirmationPassword must match. There is no built-in attribute for this, so we need to write our own. MVC 2 already had support for writing your own validation attributes, but this has been enhanced with MVC 3.
The ValidationContext is new in MVC 3 – this gives us context within which we can perform validation. In MVC 2 we can only apply validation on a single field – we don’t know what the other values have been set to.
How to do this in MVC 2
This behaviour is completely possible in MVC 2, it’s simply a little more complex. Since the we don’t have the ValidationContext object, we need to do our custom validation in the controller.
This yields exactly the same behaviour. So what’s the big deal – we’re still using exactly the same amount of code – it’s just in a different place?
The difference is that we need to remember to explicitly call this validation code every time we want to validate this model. With validation attributes we can keep all the code in one place which is much neater. The modifications to the validation helpers give us extra flexibility in dealing with different validation scenarios.
Further Reading
Scott Guthrie did a brief explanation on the validation enhancements when he announced the first preview of MVC 3.
Happy coding.