#1. Validate EmailAddress on the Form
I have a backend form class with an emailAddress
property that has validation logic so that I can return an error message back to the user. I validate all form inputs with something like:
$form->fillWith($request->input());
if($form->validate()){
$form->dispatch($command); // if synchronous, form takes command's messageBag
}
return response($form->getMessageBag()->toJson());
#2. Validate EmailAddress Value Object in the Command Handler
I have a command handler that will take the primitive string email and create a value object. The value object will throw an exception on creation if the email is invalid:
public function handle($command){
try {
$emailAddress = new ValueObjects\EmailAddress($command->emailAddress);
// create more value objects...
// do something else with the domain...
} catch (DomainException $e) {
$this->messageBag->add("errors", $e->getMessage());
} catch (\Exception $e) {
$this->messageBag->add("errors", "unexpected error");
}
return $this->messageBag;
}
In #1, I want to capture validation early before I dispatch a command. But then in #2 that validation logic is repeated when I build VOs.
Issues I have:
- If I need to change validation requirements on email addresses, then I have to update both places.
- If I use VOs on my form then I will have to deconstruct them again when passing to the command. Also, if my form is in a different Bounded Context then I will have VOs leaking domain from the other Bounded Context (maybe this is necessary?).
So my question is, should I create some validator objects that both my form validation and VOs can share/utilize? Or how do I capture repeated validation concerns between forms and value objects?