MVC 3 and DRY custom validation

一个人想着一个人 提交于 2019-12-02 00:17:48

OOTB: http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.98).aspx

You aren't really validating DRY here. The concept of DRY is a bit more nuanced than simple duplication of code. There are acceptable tradeoffs, especially when coupling concerns are taken into account.

When people ask this question, which is quite often if you search around, I usually refer them to the DDD concept of bounded concepts. Using [Remote] and forcing DRY when it comes to validation tends to bunch up tons of concerns in one place and merging the responsibilities of several layers. Business Logic vs. Persistence and Data Integrity Logic ( non nulls ).

@Darin Dmitrov says it pretty well in a lot of his answers he's made to this exact question. Validating that a required field is filled in is much different from making sure Sally has enough credit to make a purchase and should be treated much differently.

Client validation is best used for basic concerns and not be overloaded with more heavy operations. The impact on usability from client validation is really minimal. There is nothing "unusable" about posting a form and waiting for a refresh. It is more fluent but not anything that will make or break the success of your application.

AFAIK, there is nothing OOTB (Out Of The Box).

As for the tradeoffs - though violating DRY, you gain several things:

  • Immediate feedback to the user (improved usability)
  • No round tripping in case of validation errors (less load on server)

Of course, apart from violating DRY and opening yourself to those issue, you also end up with a larger payload to the client (extra javascript).

No one can tell you whether these tradeoffs are worth it - you need to decide what is right for your application, users and client.

I don't really share your concerns about violating the DRY principle in this case, but it looks like a couple other people have already discussed that.

However, your idea sounds a lot like the new remote validation feature that was added with MVC 3:

How To: Implement Remote Validation in MVC3

On the other hand, nothing is stopping you from having all of the built-in simple checks performed on the client side, and doing all of the heavy custom validation only when posting back to the server.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!