简体   繁体   中英

Does IClientValidatable implementation violate the DRY principle in MVC?

MVC provides a lot of validation attributes which can be used as data annotations to perform simple server-side validations.

However, if I want to do some custom validation using my own business logic, I need to create a custom validation attribute, derived from ValidationAttribute , and override the IsValid method.

So far so good.

However, if I want to perform the same validation on client side, I need to implement the IClientValidatable interface in my validation attribute class, and implement the GetClientValidationRules method, which will tell my application that this validation has to be performed on the client-side too.

The contentious issue however, is that I need to write the logic for this client-side validation as separate JavaScript using jQuery. This is exactly the same logic I already wrote in C# (or VB) when overriding the IsValid method.

Why do I have to write the same logic twice, albeit in different languages? Doesn't this violate the DRY principle? I would have expected MVC to generate the JavaScript for the validation logic itself.

Example illustrating what I am talking about: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/enabling-client-side-validation-on-custom-data-annotations-w/

EDIT:

Also, what if my validation logic requires data from the application config file or application cache? How do I use that in the jQuery method I write for client-side validation? If I can't, is there any other way to do client-side validation, the logic for which uses application data?

Yes, but it's often worth it.

The benefits of client side validation are speed and less server load. The benefit of server validation is security. Implementing both gains the best of both worlds.

DRY is a good rule of thumb, but as with all rules of thumb there are situations in which the rule should be violated.

EDIT to answer your follow up question

If your jQuery needs values from server side config you need to pass that to the client as part of the JavaScript. For example, you could define a variable in your view which holds the server side value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM