使客户端和服务器端验证规则相同

问题描述:

我有谁使用ASP.NET MVC和KnockoutJS的MVVM部分的应用程序。
服务器中的数据绑定到由JSON服务器。
客户请客数据并进行后一个标准的POST回调。

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 :


  • 的property1必须高于10,如果property2 ==FOOBAR

  • 的property2必须!=

等等...(有很多的条件,我要处理)

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

因此​​,为了使事情变得更简单,是有可能避免服务器端code(C#)和客户端(JS)之间code重复?
这个想法是在一个地方(使用数据注释也许)来定义的验证规则,并利用这些规则来生成JS code(对于客户端验证)或C#code(服务器端验证)

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).

感谢由前进!

我想象的建在注释的结合将jQuery验证会适合你的大部分的业务需求。

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]

有关要求的东西一点点额外的(像你提到的第一个场景)中的那些,你既可以看看Remote$c$c>验证 实现自己的注解(但会有点麻烦挂钩到jQuery验证时添加新的注解)。

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).