Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC ViewModel validation and Single Responsibility Principle [closed]

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?

like image 759
Mateusz Dudek Avatar asked Jan 24 '26 18:01

Mateusz Dudek


2 Answers

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.

like image 74
thmshd Avatar answered Jan 26 '26 10:01

thmshd


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.

like image 31
Yogi Avatar answered Jan 26 '26 10:01

Yogi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!