MVC – Should the View Perform Validation?

Architecturemvc

I was reading "In MVC should a model handle validation?" because I was curious about where validation logic should go in an MVC website. One line in the top answer goes like this: "controllers should handle validation, models should handle verification."

I liked that, but it left me wondering why we wouldn't do data validation in the View, for several reasons:

  1. Views typically have robust validation support (JS libraries, HTML5 tags)
  2. Views can validate locally, reducing network IO
  3. UI is already designed with data-type in mind (calendars for dates, spinners for numbers), making it one small step from validation

Validating in more than one place is contrary to MVC's concept of isolating responsibilities, so "do it in both" seems inappropriate. Is doing data validation only in the controller truly the dominant approach?

Best Answer

I don't think there is a single place where you can say all the validation should go. This is because we have a few different competing programming strategies working together in a standard asp.net mvc website.

Firstly we have the idea of separating the domain logic into models, the 'action' logic into controllers and the display into a View. This is based on the idea the all the logic will take place on the server with the browser simply providing a render of the view.

Then, we extend the View by using client side javascript. This is so advanced these days that the 'one page website' idea with Jquery/knockout/angular is common practice.

This practice can be equivalent to writing a whole client side application which itself implements a MVC or MVVM pattern. We denigrate the View to a Data Transfer Object and the Controller to a service endpoint. Moving all business and UI logic into the client.

This can give a better user experience, but you are having to trust an essentially untrustworthy client. So you still need to carry out validation logic on the server, regardless of how well your client pre-validates its requests.

Also, we often have validation requirements which cant be carried out by the client. eg. 'is my new Id unique?'

Any application you create with the goal of giving the best experience/performance will necessarily borrow for multiple programming paradigms and make compromises on them to achieve its goal.