Reputation: 24308
I am using automapper to map my models to viewmodel classes to pass to my view.
My question really is where should the validation go? I was planning on using the MetaData decorations - a feature of mvc 2.
But either in the model or viewmodel? Or in both places?
Upvotes: 6
Views: 299
Reputation: 5256
You should put validation that is specific to the UI in the ViewModel, and anything that is related to business process or database validation in the Model. These might overlap.
Upvotes: 1
Reputation: 1061
The model should implement the validation it needs to ensure that its state cannot become invalid; that validation most definitely belongs on the model. for example, a book class must guarantee that its title must be between 1 and 50 characters, its id must be >= 0 etc.
business rules belong elsewhere (in your controllers if you only have the model view and controller layers). this might be something like a user cannot add more than 3 books if their email isnt verified.
validation in the view should be restricted to parsing user input for invalid data: anti xss, sql injection, out of range. etc
Upvotes: 0
Reputation: 16532
I personally have my validation 2 places using DataAnnotations. My model is not passed up to my view in full. I have separate models for my views and translate the data from the view model into the model. This way, I can put whatever I want in my view model and leave out the pieces I don't want to deal with.
My reasoning, however, is that I have a windows application and an web application using the same model. This way, the same set of validation rules govern the Model for all apps, and my view model can have slightly different rules if need be. Of course, this creates a "duplication of logic" - well, validation logic.
This way I don't have to rebuild the data that wasn't used on the page every trip back to the server or put it in hidden fields and inflate the size of my pages.
Upvotes: 1
Reputation: 6085
My answer would be ViewModel because Model can change (for example from using Linq2SQL to EF). This way when you plug another Model you still have your validation intact.
Upvotes: 1
Reputation: 1038770
Validation should be done minimum at the View Model because this is what you receive as action argument and contains the user input. You could also have validation at the model.
Upvotes: 4