3

The most common approach I've seen in online examples when it comes to validation in MVC is to use the ViewModel to validate the data. People either use Data Annotations or implement IValidatableObject and IClientValidatable interfaces. But doesn't that break the Single Responsibility Principle? Should the ViewModel really be responsible for validation?

One approach I thought of is to create a separate validator class and pass it the ModelState dictionary from the controller. The downside to this approach is that we lose the ability to perform easy client-side validation by implementing IClientValidatable interface and using the JQuery validation library.

What would be the correct way to implement ViewModel validation in MVC without breaking the SOLID principles?

tereško
  • 58,060
  • 25
  • 98
  • 150
Mateusz Dudek
  • 103
  • 1
  • 6
  • 1
    There are two levels of validation. A simple formal validation you can implement client-side or with data annotations at the server. And then costly business validation that involves multiple dependencies to other data / other systems. I guess usually then there is no "either/or" but rather you need both. – Wiktor Zychla Jun 15 '16 at 10:41

2 Answers2

1

It's possible to create custom validation attributes. You can still achieve unobtrusive client side validation when implementing some snippets of JavaScript code. In your custom attribute, you could inject your validator class instance.

That said, I think that it's fine to ensure simple validation rules (required fields, length etc.) in the View(-Model) only. In this (old and now mainly obsolete) blog entry Steve describes the stages of validation as a "continuous spectrum" where rules are enforced continuously. You can grab some ideas from that entry. Hope that helps.

thmshd
  • 5,729
  • 3
  • 39
  • 67
1

I think it is fine. It should be perfectly alright for a class to know what makes it a valid class. Moreover it also makes the implementation very flexible and reasonable.

There are always trade-offs when we apply any design thought. To implement them in their purest form may not be feasible at times and at times it could lead to over-engineered code with constraints of its own.

Single Responsibility Principal for example, look very simple on books, but understanding and defining what is THE single responsibility is really a task. For some person communication with a DB could be a SR, but you know it is not just that, there are many more responsibilities, when we drill it more. On the other hand if we go by the principal in its purest form, possibly we will not have more than a method in the class.

So for most of the solutions, I personally like to tighten the strings just enough for that melody. Somewhere reasonably in equilibrium.

Yogi
  • 9,174
  • 2
  • 46
  • 61