views:

473

answers:

3

Where should validation reside when using ViewModels with MVC (MVVM), on the Model or the ViewModel? (Or both or neither)? And why? I bring this up especially in light of V2 of ASP.NET MVC coming out soon.

What about complex/custom validation?

+9  A: 

Any business specific validation should be in the Model. Any web site specific validation could be done in both the Model and/or ViewModel. This way your business logic (Models) can move behind a different interface (Windows, Web Forms, etc.) and your validation will stay intact.

mc2thaH
+4  A: 

Model. Your validation should be in your business layer. Your view model should be just for getting your view setup.

Kelsey
+6  A: 

I would say it is often needed to validate at all levels :)

I was thinking for a while about following:

  1. User input validation: definitely on the controller, not on any type of model. Example: Captcha.
  2. View related data validated on the ViewModel (not IN the ViewModel, but ON the ViewModel). Examples: Password confirmation, Required Email.
  3. Business rules validation definitely goes into Model validation. Examples: Required Email, Discount coupon should be valid.
  4. Potentially Use-Case (story, scenario etc) validation. It does not validate the attributes, but validates the correctness of the whole process. Should go to Model validation (or better in a separate layer). Example: Only 3 items can be obtained for free during a week if no order has been put for the given period.

NOTE: I included the Required Email into both 2 and 3 as it often depends where it belongs.
If the Email plays only informative role - then the validation can be relaxed and push it to the view-model. If Email is a strong requirement for the application - it is definitely model validation.

The 4th thing has actually nothing to do with validation as we understand it.
But it should also be applied. Thus its result should be displayed to user.

Basically all 4 types of validation can use the same infrastructure. But the implementation depends :)...

Cheers,
Dmitriy.

Dmytrii Nagirniak