>I’m working on a new (and simple) site in ASP.NET MVC v2 in v4 of the framework. And I’ve been trying to figure out the best way to do validations using the new capabilities. But after looking at everything, I’m thinking my old way is better.
In my previous MVC sites, I’ve put the validation logic in a service layer. For client-side validation, I used the JQuery Validation Library. This did require me to write the validation logic twice but, for the complex validations, I was able to reuse my service layer code because of the capabilities of the validation library.
I use view models in my UI. Using the definitions from Simon Ince’s Blog, I use a combination of variant 2 (Container View Model) and variant 3 (View Model and Mappers).
To get the validation messages from the service layer to the UI layer, I used the IValidationDictionary and ModelStateWrapper approach talked about in the this ASP.NET MVC tutorial.
And this approach worked well for me.
Now I’m moving into MVC v2 and am looking at the new validation capabilities with the data annotations library. I liked what I saw. Not having to duplicate the validation code in both the client and server was going to save lot’s of time.
As I started looking at implementing it, I got my first concern. All of the validations were being placed in the View Models, not on the domain models. When I found samples with the validations placed on the domain models, the domain models were being used as the view models. Sigh…
When I did some research, I discovered that the data annotation validations have MVC dependencies. So using them in a service layer seems like a bad idea. Another sigh…
But if I move away from the new validations framework and from using View Models with Mappers, that also makes it more difficult to use the templates because I’d lose the DisplayName attribute. And I find that attribute and the templates incredibly handy, helpful and time saving.
So, for now I’m thinking I will be coding validations twice and they will execute three times; once on the client, once on the server in my UI and once on the server in my service layer. Seems like a waste but I don’t see any other approach right now.