Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practices for avoiding validation logic duplication when working with both domain objects and view models in ASP.NET MVC

Common scenario:

Hierachical domain model is being mapped to flat view model for presentation purposes.

I have a full validation setup in my domain and would like to avoid mapping view model to domain object just to find out that some property is invalid. Nor do I want to duplicate my validation logic in my view models.

What are some good practices here?

I'm against interfaces for both view models and domain objects, since view models are usually stringy and flat, whereas domain objects are often nested and have many other data types for properties.

I'm thinking about some pluggable validator that will be smart enough to validate both domain objects and view models but a bit skeptical about implementation.

But for simplicity I'm leaning towards this approach:

Server side validation happens only in domain model; view models are not validated, but data is validated on the client with JavaScript. So in most cases my view models will be valid and validation logic will stay in one place and will occur only in domain model. This approach has a drawback that asp.net mvc 2 validation will not be able to support it. What do you think?

Thanks.

like image 645
Valentin V Avatar asked Jan 17 '10 16:01

Valentin V


2 Answers

The Microsoft Enterprise Library offers such a 'Pluggable Validation' library which is based on generics if memory serves.

I didn't like the way that it worked, not to mention the number of dependencies on other EL components but it still might be worth a look.

I'm by no means an expert in this field but I firmly believe that data should be validated just before you want to do something with it and ALWAYS before commiting to your repository. Therefore, the best place for your Validation Logic is your Business Logic Layer. Client Side validation, although pleasent for the user, makes code maintainance a nightmare and also results in code duplication which can cause problems further down the line.

Your presentation objects should, in my opinion, be DTO's. When a user submits data back to your controllers (and BLL) you can use parsers to transform the presentation objects into business objects which can then be validated.

I reccommend having a read of Rudy Lacovara's blog (aka The Angry .NET Developer). He's a very modest bloke with a lot of good stuff to say on things like this.

HTH

like image 51
Jason Summers Avatar answered Oct 17 '22 15:10

Jason Summers


There is no validation approach that fits always.

In your case, i would use mvc2 validation (with client validation) and fall back to domain validation, if viewmodel validation passes.

like image 22
Arnis Lapsa Avatar answered Oct 17 '22 17:10

Arnis Lapsa