Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Validation using Data Annotations - Model classes or View Model classes?

Is it best practice to put data validation annotations in the Model or View Model? What are the advantages/disadvantages of one approach over the other?

Curious to see where everyone is putting their validation, I am currently doing it in the model project. However I have seen a few people say this is not best practice.

like image 732
Ryan Sampson Avatar asked Jul 26 '10 20:07

Ryan Sampson


1 Answers

As far as best practices is concerned I would say: in neither of them. Validation should be separate. Frameworks such as FluentValidation allow you to completely separate your validation logic from your models. But to answer your question I would put validation into View Models as those are the classes you are binding your controller actions to. You could also have multiple View Models that are tied to the same model but with different validation rules.

like image 159
Darin Dimitrov Avatar answered Oct 07 '22 20:10

Darin Dimitrov