Domain object validation and model validation

I am using ASP.NET MVC 3 and I am using FluentValidation to validate my view models. I'm just a little worried that I may not be back. As far as I know, model validation should be performed on a domain object. Now with MVC, you can have several view models that are similar, which requires verification. What happens if a property from a domain object occurs in more than one view model? Now you double-check the same property, and they may not even synchronize. Therefore, if I have a user domain object, I would like to do a check on this object. Now, what happens if I have a UserAViewModel and UserBViewModel, so now I need to do a few checks.

In my News class, I have a Title property, which is required. In my view model, I also have a Title property, I use AutoMapper to display news and NewsViewModel. So this check happens twice. When is a domain model validated and when is a model validated?

The script above is just an example, so please do not criticize it.

+8
validation asp.net-mvc fluentvalidation
source share
2 answers

This is a subtle difference, but a check on your presentation model is to verify the correct user input and the anti-corruption layer for your domain model, while a β€œcheck” on your domain model ensures that business rules are followed. This is completely normal and you must have validation at both levels. In fact, it may be possible that the UserAViewModel has some excellent input validation from the UserBViewModel. As for your question, as a rule, I try to avoid exposing domain objects through my ViewModel and instead match them (often using something like AutoMapper), so your ViewModels are really anti-corruption layers and not bags of domain model properties. Hope this helps.

+16
source share

What happens if a property from a domain object occurs in more than one view model?

It should not be. View models should be completely separate from your domain.

Does this answer your question?

+1
source share

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


All Articles