views:

124

answers:

4

Hi, I am trying to learn Domain Driven Design and recently read that lots of people advocate creating a ViewModels for your views that store all the values you want to display in a given view.

My question is how should I do the form validation? should I create separate validation classes for each view, or group them together? I'm also confused on what this would look like in code.

This is how I currently think validation and viewmodels fit in to the scheme of things:

View (some user input) -> Controller -> FormValidation(of ViewModel) -> (If valid map to ViewModel to Domain Model) -> Domain Layer Service -> Infrastructure

Thanks!

P.S. I use Asp.net MVC with C#

A: 

I suggest you put your validation rules in your domain model. This is the most easiest and repetitive way (use System.ComponentModel.DataAnnotations, for example - MVC 2 default model binder supports it out of the box).
If you have complex and big wide domain model and you don't won't be stuck with mapping properties having the same names - try using AutoMapper, which is awesome tool for doing this kind of work.

chester89
A: 

Validate view model on presentation layer. Keep in mind that You should validate presentation related validation only (date is in correct format, name != "", etc.).

Asp.net Mvc has some in-built validation support that usually is enough for basic validation.

Tricky part when applying domain driven design is domain validation. There might be complex rules, dependencies on repositories and similar stuff that could make 'validation running' without making domain model dumb quite hard.

Therefore - it seems like a good idea to never let domain object slip into invalid state and just throw exception in case that happens.


Better do not try to mechanically map view model to domain model - this approach increases coupling, might break encapsulation of Your domain model and dumb it down.

Arnis L.
A: 

I have been experimenting with placing my form validation in the ViewModel, and for complex business validation I use a service layer.

This has actually been working out real well and the code is so much easier to read and maintain

chobo
A: 

This is a common question and it's one that doesn't always have one correct answer. Check out this post by Derick Bailey. It's a good discussion on this question and has several links to some other great posts on the issue.

MrDustpan