ASP.NET MVC - avoid duplicate validation code in JavaScript and C # and with context validation that takes into account other property values?

How can you avoid duplicating validation code in JavaScript and C # in ASP.NET MVC 3, also an example with context validation, which takes into account other properties, is desirable?

Does ASP.NET MVC 3 provide the ability to avoid duplicating the validation logic in C # and JavaScript when you need custom validation? For an example of such duplication, which I am talking about, see the blog post http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx , and a comment added by "Ali Nov 20, 2009 12: 19 AM ", that is, the C # if" if (cents <0.99 || cents> = 0.995) {"operator, which exists similarly in javascript code.

Is it still (with ASP.NET MVC 3) impossible to define the validation logic only once? For example, I think it should be possible to write C # code that defines the verification metadata model, and then such a model can be used by C # code, as well as to automatically create javascript code?

If it is still not supported by the MVC 3 framework, are there possibly any external validation libraries that can be used to generate JavaScript validation without the need for duplication?

For example, if any of the http://fluentvalidation.codeplex.com/ or http://specexpress.codeplex.com/ frameworks does support automatic generation of client verification code, then someone can provide a link that illustrates how use it, and assemble all parts without any duplicated (with C # and Javascript) verification code?

It would also be interesting to see an example of code with contextual validation that can sometimes validate a property (that is, without using the hardcoded attribute “[Required]”, as if the property was always required in all contexts) or with different validation rules (depending on values ​​of some other property). For example, let's say you have a drop-down list with countries and a drop-down list with states. If you choose a country in which there really are states, then for verification it is necessary that the state be also selected, but for other countries that do not have any states, then validation should not be applied. How can I perform such a check that works both on the client side and on the server side with a minimum amount of JavaScript code that must be implemented manually (i.e. I would like to create only a C # verification model that can generate appropriate javascript validation)?

+4
source share
1 answer

If you use jQuery.validate, you can reduce duplication to one function - the actual validation. Here's an example of how to check if the two properties are the same — basically the “depending on the value of some other property” you are looking for.

http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

0
source

Source: https://habr.com/ru/post/1340941/


All Articles