Make client-side and server-side validation rules the same

对着背影说爱祢 提交于 2019-12-09 22:18:58

问题


I have an application who use ASP.NET MVC and KnockoutJS for the MVVM part. The server bind the data to the server by JSON. The client treat data and make a standard POST callback after that.

I have now to handle some business logic like :

  • The property1 must be superior to 10 if property2 == "FOOBAR"
  • The property2 must be != ""

Etc etc... (there is a lot of conditions I have to handle)

So, to make things simpler, is it possible to avoid code duplicate between the server side code (C#) and the client side (JS) ? The idea would be to define the validation rules at one place (using Data Annotations maybe) and use these rules to generate the JS code (for client side validation) or the C# code (for the server side validation).

Thanks by advance !


回答1:


I would imagine that the built in annotations combined with adding jQuery validation would suit most of your business requirements.

For example, your second one can be achieved using [Required]

For the ones that require something a little extra (like the first scenario you mentioned), you could either take a look at Remote validation or implement your own annotations (but that gets a little trickier when hooking into jQuery validation to add your new annotations).



来源:https://stackoverflow.com/questions/16062614/make-client-side-and-server-side-validation-rules-the-same

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