asp.net-mvc

MVC validation: where to validate?


We say that model validation at controllers layer is the correct place to validate all data we gonna operate with. In this case, if we change UI to another (remembering that our layers must be pretty decoupled) the new data validation principles are going to execute - in this case all our inner rules can be violated. You may say that data models is the separate layer and that layer, but not UI, is the only place for validation. But in this case i found it more effective to validate data in the service or business objects layer, don't i? In fact we have a number of objects corresponding to our domain object: db table record, linq2sql class, domain object class, viewmodel class. Should it be only one place to validate data model? Why should it be in (or close to) UI but not in the other layer? In my opinion, the validation must occur in the service layer - with all other busness logic. If i need to inform user about error as fast as possible, i'll use client validation in addition to main one.

Thoughts?


Solution

  • Data validation is the responsibility of the model. The best place to put validation rules in my opinion is as constraints in the database. Having constraints ensures that no incorrect data will ever be stored in the database, no matter how it is accessed. Unfortunately only basic constraints are suitable to express in the database.

    The next place to put validation, when using linq-to-sql for data access, I is the extension methods on the entity classes. Then all code will have to pass through the validation.

    To improve user experience, basic validation can be repeated in the UI, but that is just for user experience and to catch the most common mistakes early. On the web, using JavaScript validation is preferable. On rich clients the same code as the one called by the extension methods can sometimes be reused.

    Always remember that any service exposed to a client, could be called by a malicious client that lacks the validation that the real client does. Never trust the client to do any kind of validation or security checks correctly.