phpvalidationmodeldomain-driven-design

Define "Validation in the Model"


There have been a couple of discussions regarding the location of user input validation:

Should validation be done in Form objects, or the model?

Where do you do your validation? model, controller or view

These discussions were quite old, so I wanted to ask the question again to see if anyone had any fresh input. If not, I apologise in advance.

If you come from the Validation in the Model camp - does Model mean OOP representation of data (i.e. Active Record/Data Mapper) as "Entity" (to borrow the DDD terminology) - in which case you would, I assume, want all Model classes to inherit common validation constraints. Or can these rules simply be part of a Service in the Model - i.e. a Validation service? For example, could you consider Zend_Form and it's validation classes part of the Model? The concept of a Domain Model does not appear to be limited to Entities, and so validation may not necessarily need to be confined to this Entities.

It seems that you would require a lot of potentially superfluous handing of values and responses back and forth between forms and "Entities" - and in some instances you may not persist the data recieved from user input, or recieve it from user input at all.


Solution

  • When handling user input, you should definitely handle all logic-oriented validation outside the model.

    The model doesn't care about your business logic. The model doesn't care if your start date is after your end date - all the model cares about is that the date is a valid entry for that particular field in the database. It checks the data, sees a properly formatted date and moves on to the next one, because the model's entire realm of responsibility is to ensure the smooth flow of data to and from a data source.

    Classes like Zend_Form are nothing more than abstractions of your view.