Lesson 38 of 45 · Failure and Validation
Input Validation vs Domain Validation: Where Each Belongs
The validation that exists in three places
A guest registers. The email "must be a valid email address" gets checked in three places in the PHP:
In the form request, with
'email' => 'required|email'.In the DTO's
fromArray, with afilter_var(...)defensive check.In the
EmailAddressvalue object's constructor.
A Vue component on the front end may check it a fourth time. Each one is doing some version of the same validation. Some agree exactly. Some agree mostly. One has a subtly different regex that nobody remembers writing. When the rules change (allow + in the local part, require a TLD, restrict to certain domains), three files have to change. Two of them get changed. The third one quietly disagrees.
This is the validation problem in long-lived codebases. It's not that validation is wrong; it's that the team never agreed on where it lives, and the rules drifted across all the places it ended up.
Two distinct kinds of validation
Input validation. "The user sent us this. Is it well-formed?" Did they include the required fields? Are the strings strings? Is the date a date? Is the email syntactically an email?
This is request-shaped. It happens at the system boundary, where untrusted input enters. It's about whether the input is parseable into the shape the rest of the system expects. The question is: "should we even try to do anything with this, or reject it now?"
Invariant validation. "Given some inputs, is this a valid domain object?" Can a Money be negative? Can a reservation's check_in be after its check_out? Can a GuestCount have zero adults?
This is domain-shaped. It happens inside the business code, when domain objects are being constructed or mutated. It's about whether the proposed domain state is internally consistent. The question is: "does this state make sense in the world we're modeling?"
These two are different and want to live in different places. The reason the same validation shows up in three files is that the line between them got blurred.
Input validation at the boundary
Input validation belongs at the request boundary. In Laravel, that's the FormRequest:
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
final class RegisterGuestRequest extends FormRequest
{
public function rules(): array
{
return [
'email' => ['required', 'email:filter'],
'password' => ['required', 'string', 'min:8'],
'name' => ['required', 'string', 'max:255'],
];
}
}The email:filter rule runs PHP's filter_var with FILTER_VALIDATE_EMAIL, the same call EmailAddress makes later in this lesson (FilterEmailValidation in Laravel's ValidatesAttributes concern). It is the one deliberate copy: it exists so the user gets a field error in the 422, and EmailAddress is where the rule lives.
The job here is "is this request even worth processing?". If it isn't, the framework rejects it before the business code ever runs: a 422 with field-level errors for JSON requests, a redirect back with the errors for a normal web form. The handler doesn't have to think about malformed input.
Symfony reads the same boundary from the DTO. A controller argument marked #[MapRequestPayload] is filled from the request body and validated with the constraints on the DTO's properties, such as #[Assert\Email] on an $email property. A failure gives a 422 by default, the validationFailedStatusCode of MapRequestPayload. Assert\Email defaults to an HTML5 pattern, not filter_var, so on Symfony the two checks can disagree on rare addresses.
The input layer also handles cross-field rules that depend on the request shape: "if country_code is US, state is required". "If payment_method is card, card_number is required". These belong in the request layer because they're about the input, not about the domain.
Input validation should be the only place that knows about HTTP-shaped concerns: required fields, presence checks, conversion from strings.
Invariant validation in the domain
Invariant validation belongs at the domain layer. Specifically, on value objects and entities. EmailAddress is the class from earlier in the course, trimmed to the constructor check:
<?php
declare(strict_types=1);
namespace App\Booking;
use InvalidArgumentException;
final readonly class EmailAddress
{
public function __construct(public string $value)
{
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email: {$value}");
}
}
}Guest is the class from the previous lesson with a name guard added. InvalidGuestState is a domain exception in App\Booking\Exceptions that extends App\Framework\Exceptions\DomainException, and isn't shown. Over HTTP the form request's required rule and Laravel's TrimStrings middleware already reject a blank name, so the guard is for callers that don't come through a request:
<?php
declare(strict_types=1);
namespace App\Booking;
use App\Booking\Exceptions\InvalidGuestState;
use DateTimeImmutable;
final class Guest
{
private function __construct(
public readonly GuestId $id,
public readonly EmailAddress $email,
public readonly string $name,
private string $passwordHash,
private DateTimeImmutable $registeredAt,
) {}
public static function register(
EmailAddress $email,
string $name,
string $passwordHash,
DateTimeImmutable $registeredAt,
): self {
if (trim($name) === '') {
throw new InvalidGuestState('A guest cannot be registered without a name');
}
return new self(GuestId::next(), $email, $name, $passwordHash, $registeredAt);
}
}The job here is "given these inputs, is the resulting domain state valid?". If not, the constructor or method refuses to build the object. Every consumer of the domain object gets the guarantee that the state is consistent.
This kind of validation doesn't care where the input came from. It cares about the rules of the domain itself. An EmailAddress is just as wrong if it comes from a webhook, a CSV import, or a queue worker as it is from an HTTP request.
Both constructors throw. EmailAddress throws InvalidArgumentException, which over HTTP can't be reached because the form request runs the same check first. From a webhook or a console command it is a 500 unless that caller catches it. InvalidGuestState extends DomainException, so the bootstrap/app.php mapping from the domain exceptions lesson turns it into a 422.
The command is the seam
The two kinds of validation meet at the command (a DTO). It is built from the validated request input and carries it inward as plain strings, where the domain layer picks up its own validation. The fromArray filter_var check from the opening list goes, because the form request and EmailAddress already cover both ends. The controller builds the command from $request->validated() and passes the handler's result to a respond() method. respond() gives both outcomes this lesson's handler returns the same 202 as the previous lesson's match, sending the sign-in link for a taken email, and SignInLinks is the previous lesson's interface:
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Booking\RegisterGuestCommand;
use App\Booking\RegisterGuestCommandHandler;
use App\Booking\Results\EmailAlreadyInUse;
use App\Booking\Results\RegisterGuestResult;
use App\Booking\Results\RegistrationSucceeded;
use App\Booking\SignInLinks;
use App\Http\Requests\RegisterGuestRequest;
use Illuminate\Http\JsonResponse;
final class RegisterGuestController
{
public function __construct(
private RegisterGuestCommandHandler $registerGuest,
private SignInLinks $signInLinks,
) {}
public function __invoke(RegisterGuestRequest $request): JsonResponse
{
$data = $request->validated();
return $this->respond($this->registerGuest->handle(new RegisterGuestCommand(
email: $data['email'],
name: $data['name'],
password: $data['password'],
)));
}
private function respond(RegisterGuestResult $result): JsonResponse
{
if ($result instanceof EmailAlreadyInUse) {
$this->signInLinks->sendTo($result->email);
}
return new JsonResponse(['message' => 'Check your email.'], 202);
}
}The handler is the previous lesson's, trimmed to the registration path (no password policy, no event, no duplicate-email race). RegisterGuestCommand is the command from the previous lesson (the DTO above), GuestId is from the Primitive Obsession lesson, and Guests is the interface the previous lesson uses, built as a fake in a later lesson. All three are in App\Booking:
<?php
declare(strict_types=1);
namespace App\Booking;
use App\Booking\Results\EmailAlreadyInUse;
use App\Booking\Results\RegisterGuestResult;
use App\Booking\Results\RegistrationSucceeded;
use Illuminate\Contracts\Hashing\Hasher;
use Psr\Clock\ClockInterface as Clock;
final readonly class RegisterGuestCommandHandler
{
public function __construct(
private Guests $guests,
private Hasher $hasher,
private Clock $clock,
) {}
public function handle(RegisterGuestCommand $command): RegisterGuestResult
{
$email = new EmailAddress($command->email); // domain validation: throws if not a valid email
if ($this->guests->withEmail($email) !== null) {
return new EmailAlreadyInUse($email);
}
$guest = Guest::register(
email: $email,
name: $command->name,
passwordHash: $this->hasher->make($command->password),
registeredAt: $this->clock->now(),
);
$this->guests->save($guest);
return new RegistrationSucceeded($guest);
}
}Both layers look at the email, but they answer different questions:
The form request's
email:filterrule is an early copy of the format check, so the user gets a field-level error before any business code runs.The
EmailAddressconstructor holds the rule for what counts as a valid address, and the handler'swithEmaillookup decides whether it is already taken.
When the rule for a valid address changes, EmailAddress changes first and the form request rule follows it.
Symfony Messenger can run the same kind of check at the bus boundary. Its ValidationMiddleware validates the command before the handler and throws ValidationFailedException for any violation.
"Validate once, trust thereafter"
The principle that ties this together:
Validate once, at the right boundary. Trust the validated objects from there inward.
Once a piece of data has been validated by the form request, you don't re-validate it in the handler. Once a value has been wrapped in an EmailAddress, you don't re-validate the format. The type system carries the guarantee.
The Guard Clauses lesson applies the same idea inside a method: check at the top, then trust the rest.
The benefit is real: the rules live in one place, the rest of the codebase doesn't have to think about them, and changes propagate from one source. The cost is one-time: investing in proper value objects and request classes upfront. For a small project with no rich domain, validation in the request layer alone is fine. The value objects earn their place when the domain has invariants worth enforcing in code.
Uniqueness needs the database
"Email is already taken" can't live in the form request or a value object, because it needs a lookup. It runs in the handler as a Guests::withEmail call that returns EmailAlreadyInUse. A unique: rule in the form request can pass for two simultaneous requests, so the database's unique index is the real guarantee. The domain exceptions lesson shows EloquentGuests::save() turning an index violation into DuplicateGuestEmail, and the registration handler turns that into EmailAlreadyInUse.
Pitfalls
Domain validation in the form request. Copying the EmailAddress rule into the form request in a different form, such as a hand-written regex, while the value object keeps its own. The two drift. Use the framework rule that runs the same check (email:filter), and let the value object own the rule.
Request validation in the domain. A domain method that throws because "the request didn't include a country_code" is doing the form request's job. The domain shouldn't even know about the request. By the time the data reaches the domain, the missing-field case should have been rejected.
Mixing validation with business logic. A method that validates an input and also does the work is doing two things. Guard clauses are the right shape: validate at the top, do the work below. The two pieces stay separable.
The one thing to remember
There are two kinds of validation, and they live in two different places:
Input validation (is this request well-formed?) → form request at the boundary.
Invariant validation (is this domain state consistent?) → value objects and entities in the domain.
The command is the seam between the two. Pick one place that owns each rule, validate there, and trust the result downstream. In the codebases I've worked on, duplicated validation came from the team not agreeing on which kind of rule a given check was, and putting it in both places to be safe.
Related Links
- ValidationLaravel's docs on form request validation, the boundary layer this lesson describes.
- ValidationSymfony's Validator component, its constraints-based approach to the same boundary problem.
- Where does my validation live?Frank de Jonge on splitting validation across the controller, service, and domain layers.
- filter_varThe PHP manual page on FILTER_VALIDATE_EMAIL, used in this lesson's EmailAddress value object example.