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 !
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