With the new ASP.NET MVC 2 validation features, we can decorate the properties of our domain model objects with DataAnnotations
attributes that describe criteria for valid values. The DefaultModelBinder
knows about this and populates ModelState.IsValid
accordingly before a controller action is invoked. Since the validation rules are defined within the domain model, this is regarded as model-level validation. Scott Guthrie writes:
The benefit of implementing the rules within our Person object is that this will ensure that the validation will be enforced via any scenario within our application that uses the Person object [...]
Strictly speaking, the rules are not really enforced in my opinion, since all the action methods need to check the ModelState.IsValid
property and act differently depending on its value. Also, although the rules are defined in the model, they are applied in the presentation layer since that's where all model binders live. But I guess this is just me being picky with the choice of words (or me just being plain wrong).
However, what about enforcing the validation rules at the domain model level? Steven Sanderson uses this approach in a post about the xVal validation framework where he writes:
Now, the model tier enforces its own validity by refusing to place bookings that don’t meet all validation and business rules.
In his example, the "booking manager" (which lives within the model) throws a special business rule exception when consuming code tries to place a booking that is invalid. Thus it is impossible for the consuming code to place an invalid booking, regardless of whether it checked the validity of the booking beforehand (through ModelState.IsValid
or some other custom construct).
So my question is:
Assuming that there are validation rules defined at the model level, should they also be enforced within the model?
(Note that I'm really new to the concept of domain-driven design, so please bear with me if I haven't used precisely the correct terminology.)