I am using ASP.NET MVC 3 and I am using FluentValidation to validate my view models. I am just a little concerned that I might not be on the correct track. As far as what I know, model validation should be done on the domain object. Now with MVC you might have multiple view models that are similar that needs validation. What happens if a property from a domain object occurs in more than one view model? Now you are validating the same property twice, and they might not even be in sync. So if I have a User domain object then I would like to do validation on this object. Now what happens if I have UserAViewModel and UserBViewModel, so now it is multiple validations that needs to be done.
In my News class I have a property called Title, which is a required field. On my view model I also have a Title property, I use AutoMapper to map the News and NewsViewModel. So this validation is happening twice. When does domain model validation occur and when does view model validation occur?
The scenario above is just an example, so please don't critise on it.
A framework which describes and distinguishes three approaches for validating data is then developed based on these concepts. The three approaches are external validation, internal validation and process validation.
There are two types of validations: Server side Validations. Client Side Validations.
Implement validations in the domain model layer. Validations are usually implemented in domain entity constructors or in methods that can update the entity. There are multiple ways to implement validations, such as verifying data and raising exceptions if the validation fails.
To know things better, we can note that the two types of Model Validation techniques are namely, In-sample validation – testing data from the same dataset that is used to build the model. Out-of-sample validation – testing data from a new dataset that isn't used to build the model.
It's a subtle distinction but the validation on your view model is to validate correct user input and forms an anti-corruption layer for your domain model, whereas the "validation" on your domain model enforces business rules. It is perfectly normal and you should have validation on both layers. In fact it may be feasible that UserAViewModel has slightly different input validation from UserBViewModel. As for your question, generally I try to avoid exposing domain objects through my ViewModel and instead map between them (often using something like AutoMapper), that way your ViewModels truly are anticorruption layers rather than property bags of domain models. Hope that helps.
What happens if a property from a domain object occurs in more than one view model?
This shouldn't happen. View models should be totally divorced from your domain.
Does this answer your question?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With