I'd say form validation has nothing to do in domain objects. If a submitted form is invalid there usually is no reason to create/modify a domain object at all, it is an issue that lies completely in the presentation layer/user interface. Putting validation of user input into the domain objects violates the separation of concerns principle.
However, it is a controversial question and there is no absolutely right or wrong way to do it. Because if you want to ensure that a domain object can't be in an invalid state (throwing exceptions in constructor and setters) you might end up with duplicate code.
But if you use validation in domain objects for form validation or not, you should prefer exceptions over a isValid
state. The objects should always be in a valid state, this is one major advantage of OOP
Update
To the question where I put input validation: I use specialized request objects for each controller and use them in the controller like this:
try {
$user = $this->request->extractUserFromPost();
} catch (ValidationException $e) {
$this->showValidationError($e->getMessage(), $e->getAffectedFields());
}
The methods could also be in the controller itself but I prefer thin controllers that contain as little own logic as possible. Another common method are form objects that manage generation and validation of forms at one place (Example: Zend\Form
). If the request always comes from a form, this makes sense. My example above would work for a web service as well as for an HTML user interface.