Should validation rules be followed at the model level?

Using the new ASP.NET MVC 2 validation functions, we can decorate the properties of objects in our domain model with attributes DataAnnotationsthat describe the criteria for valid values. DefaultModelBinderknows about it and fills ModelState.IsValidaccordingly before calling the controller. Since validation rules are defined in the domain model, this is considered as validation at the model level. Scott Guthrie writes :

The advantage of implementing rules in our Person object is that it ensures that validation will be performed using any script within our application that uses the Person object [...]

Strictly speaking, the rules are not actually observed, in my opinion, since all action methods must check the property ModelState.IsValidand act differently depending on its value. In addition, although the rules are defined in the model, they are applied at the presentation level, since they have all the life models. But I guess it's just that I'm picky about the choice of words (or I'm just wrong).

However, what about enforcing validation rules at the domain model level? Stephen Sanderson uses this approach in a post about the xVal validation framework , where he writes:

Now the model level provides its own strength by refusing to place orders that do not comply with all the rules of verification and conducting business.

" " ( ) -, . , , , , ( ModelState.IsValid - ).

, :

, , , ?

(, , , , , , .)

+3
3

, , , ?

. , . , , , , , , , x // .

- , , , , . ( , !)

, .

+1

DataAnnotations. , , , , ASP.NET MVC . DataAnnotations System.ComponentModel.DataAnnotations. , , , MVC VS.

0

DataAnnotations ASP.NET MVC 2, , . , . , ; :

1: , ? , .., , . ; , , , . (, , , , , ).

2: (, )? .

At the end of the day, you should strive to keep your code clean and disclose intentions as much as possible, and carefully check the results. I have not yet seen any validation based on a model that really fully protects the integrity of your data in 100% of cases. Even if the user does not break your model, another developer will eventually be.

0
source

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


All Articles