Form validation and product rules: why they are different checks

A form helps correct input, while a domain rule protects valid state. An independent Symfony Form and Console example covers an empty title, a forbidden transition and a valid action without saving notes.

Two sieves with different meshes: a conceptual metaphor for input checks and domain rules.
Two sieves with different meshes: a conceptual metaphor for input checks and domain rules.

Extend the existing src/Domain/Note.php from the note creation step. The title stays readonly and EmptyNoteTitle becomes a subtype of the shared NoteRuleViolation. Preview uses a new object in memory and leaves the existing MySQL note creation store intact. Add the shown NoteTest methods to the earlier tests in the same class, preserving title checks.

A form can accept every field and still provide no grounds for carrying out an action. A note has a title, the selected option is valid, but the request to publish targets a draft that has not reached its prepared state. This is not an input error. It is a disallowed state transition.

In the article about Admin, Frontend and API, I described rules that retain the same meaning across entry points. Now we will explore that idea in a small, independent Symfony example: one HTML form and one console command will work with the same domain rule. This will help distinguish useful feedback next to a field from a condition that must also hold without the form.

First, define what we are checking

Our teaching object starts as a draft. The prepare action moves it to ready, and publish is permitted only after that, producing published. Its title must be nonempty after the standard trim().

These state names describe only this model. ready does not mean an article quality assessment or an editor’s approval. We are not building a real publication system: each call creates a fresh draft in memory, checks one action and returns its result. Notes are not saved. The HTTP session supports the form’s CSRF protection, rather than storing the note’s state.

Situation Input check Domain rule
The title contains only spaces The form displays a field error The object also rejects an empty title without the form
The action is missing or unknown The form or Console rejects the unknown option The use case receives only a known action
The title is filled in and publication is selected The fields may be valid A draft cannot be published immediately
The title is filled in and preparation is selected The fields are valid A new draft can become ready

This distinction affects where the code belongs. The form knows which field to highlight and how to turn a user’s selection into a PHP value. The object knows which of its own states and changes are allowed. Approval from a form should not become a pass that other entry points have to imitate or bypass.

The boundary is not between library names. A domain rule can be expressed through a separate validation object, including a constraint in Symfony Validator. The deciding question is whether it runs on every permitted path that changes the object. If only an HTML form invokes a check, a console import can easily fall outside it. If the shared use case guarantees the check, it can protect different entry points. In this small example, the rule lives directly in the object so that the boundary is visible without additional infrastructure.

Likewise, two messages about an empty title do not necessarily mean an unnecessary check. The form needs to keep entered values on screen and help the user correct a particular field. The domain object needs to reject an invalid state regardless of whether there is a screen. These are different responsibilities. Their meaning must agree, and the same boundary cases should be checked so that one entry point does not accept data that another discards without explanation.

The next step in the shared project

We continue one teaching Symfony project, article_demo, independent of the private platform. We create it once in the first article; later steps add capabilities to the same application. All paths below are relative to the article_demo root.

composer require 'symfony/form:8.1.*' 'symfony/validator:8.1.*' 'symfony/twig-bundle:8.1.*' 'symfony/security-csrf:8.1.*' 'symfony/console:8.1.*'
composer require --dev symfony/test-pack
composer check-platform-reqs

The object protects itself without the form

Start with a specific rejection that both entry points can present. File src/Domain/NoteRuleViolation.php:

<?php

declare(strict_types=1);

namespace App\Domain;

class NoteRuleViolation extends \DomainException
{
}

src/Domain/EmptyNoteTitle.php:

<?php

declare(strict_types=1);

namespace App\Domain;

final class EmptyNoteTitle extends NoteRuleViolation
{
}

Place the nonempty title and permitted transitions in src/Domain/Note.php:

<?php

declare(strict_types=1);

namespace App\Domain;

final class Note
{
    public readonly string $title;
    private string $state = 'draft';

    public function __construct(string $title)
    {
        $title = trim($title);

        if ($title === '') {
            throw new EmptyNoteTitle('A note title must not be empty.');
        }

        $this->title = $title;
    }

    public function prepare(): void
    {
        if ($this->state !== 'draft') {
            throw new NoteRuleViolation('Only a draft can become ready.');
        }

        $this->state = 'ready';
    }

    public function publish(): void
    {
        if ($this->state !== 'ready') {
            throw new NoteRuleViolation('Only a ready note can be published.');
        }

        $this->state = 'published';
    }

    public function state(): string
    {
        return $this->state;
    }
}

The state is closed to direct writes. The client request contains no field that could assign a trusted value of ready; the object reaches that state through its own action. If publication is rejected, the assignment of a new state does not take place.

The constructor also does not assume that someone has already checked the title. This matters for Console, a test or a future import: all of them can create the object without Symfony Form. The PHP manual describes the standard semantics of trim(). The example does not extend them to every Unicode whitespace character or comprehensive text normalization.

The use case checks one action

After parsing the input, pass a known action instead of an arbitrary string. File src/Application/TransitionAction.php:

<?php

declare(strict_types=1);

namespace App\Application;

enum TransitionAction: string
{
    case Prepare = 'prepare';
    case Publish = 'publish';
}

The use case in src/Application/PreviewNoteTransition.php creates a new object and performs one action:

<?php

declare(strict_types=1);

namespace App\Application;

use App\Domain\Note;

final class PreviewNoteTransition
{
    /** @return array{title: string, state: string} */
    public function __invoke(string $title, TransitionAction $action): array
    {
        // Every preview starts from a new draft; nothing is persisted.
        $note = new Note($title);

        match ($action) {
            TransitionAction::Prepare => $note->prepare(),
            TransitionAction::Publish => $note->publish(),
        };

        return ['title' => $note->title, 'state' => $note->state()];
    }
}

This is an intentional limit of the experiment. Running prepare through the form does not save a prepared note for the next request. A new request with publish starts from draft again and should be rejected. We will check the complete allowed sequence on one object in a separate test.

In a real editorial use case, the object would be loaded with its saved state. Here, the point is to show that the domain model determines the state, while entered fields do not establish whether a transition is allowed. Persistence, concurrent changes and authorization would require their own decisions.

The form helps the user enter data correctly

The form needs an input object that can temporarily contain unacceptable values. It is not yet a valid note. File src/Form/NoteInput.php:

<?php

declare(strict_types=1);

namespace App\Form;

final class NoteInput
{
    public string $title = '';
}

Now define the form type in src/Form/NoteTransitionType.php:

<?php

declare(strict_types=1);

namespace App\Form;

use App\Application\TransitionAction;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;

final class NoteTransitionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('title', TextType::class, [
                'label' => 'Title',
                'trim' => false,
                'empty_data' => '',
                'constraints' => [new NotBlank(message: 'Enter a title.', normalizer: 'trim')],
            ])
            ->add('action', EnumType::class, [
                'label' => 'Action',
                'class' => TransitionAction::class,
                'mapped' => false,
                'placeholder' => 'Choose an action',
                'constraints' => [new NotNull(message: 'Choose an action.')],
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => NoteInput::class,
            'csrf_token_id' => 'note_transition_preview',
        ]);
    }
}

Automatic trim in TextType is disabled for the title: it removes a wider range of Unicode whitespace than PHP trim(). Instead, NotBlank with normalizer: 'trim' checks the title using the same PHP semantics and displays a field error. The normalizer changes only the value used for validation; the domain object performs the final trimming. U+00A0 therefore remains in both the form and Console. Broader normalization would require changing the shared domain rule and both sets of checks.

We explicitly set the empty value to a string through empty_data, matching the input property’s type. The input object itself permits an empty string: the user can still correct the form. Binding a domain object with a strict constructor immediately would mix ordinary editing of unfinished input with creating a valid note. Here, conversion into that note happens only inside the use case. The title is not copied into an existing object between separate checks; a new object is either created correctly or not created at all.

EnumType turns a known selection into a TransitionAction. An unknown value does not become a new object method. NotNull covers a missing selection. The action field is not written to NoteInput: the adapter reads it after form validation.

Emptiness is checked both beside the field and in the constructor. Here, those checks have different consequences: one explains an error to the user, while the other prevents an invalid object from being created. If the rule becomes more complex, the shared part can move into a separate domain check. Useful form feedback and protection of other entry points should both remain.

A valid form can still receive a rejection

The controller in src/Controller/NotePreviewController.php checks the form submission before calling the use case:

<?php

declare(strict_types=1);

namespace App\Controller;

use App\Application\PreviewNoteTransition;
use App\Application\TransitionAction;
use App\Domain\NoteRuleViolation;
use App\Form\NoteInput;
use App\Form\NoteTransitionType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class NotePreviewController extends AbstractController
{
    #[Route('/note-transition-preview', name: 'app_note_preview', methods: ['GET', 'POST'])]
    public function __invoke(Request $request, PreviewNoteTransition $preview): Response
    {
        $input = new NoteInput();
        $form = $this->createForm(NoteTransitionType::class, $input);
        $form->handleRequest($request);
        $result = null;
        $status = Response::HTTP_OK;

        if ($form->isSubmitted()) {
            if (!$form->isValid()) {
                $status = Response::HTTP_UNPROCESSABLE_ENTITY;
            } else {
                $action = $form->get('action')->getData();

                if (!$action instanceof TransitionAction) {
                    throw new \LogicException('A valid action field must contain TransitionAction.');
                }

                try {
                    $result = $preview($input->title, $action);
                } catch (NoteRuleViolation $error) {
                    $form->addError(new FormError($error->getMessage()));
                    $status = Response::HTTP_UNPROCESSABLE_ENTITY;
                }
            }
        }

        return $this->render('note_preview/index.html.twig', [
            'form' => $form->createView(),
            'result' => $result,
        ], new Response(status: $status));
    }
}

The sequence of handleRequest(), isSubmitted() and isValid() is described in the Symfony Forms documentation. After it, the transformed field values can be used. It does not mean that a fresh draft is already in a state from which publication is permitted.

That is why NoteRuleViolation is handled after the use case call. We add a transition error to the form as a general message. For this teaching HTTP contract, we choose 422 for both invalid fields and a rejected domain action; the user sees different explanations. Other programming errors are not converted into this message.

These rejections differ in practical terms on screen. For an empty title, the user changes the field. For a disallowed transition, changing the spelling of the title will not help: a different permitted action on the appropriate state is needed. That is why the transition message is not attached to the title. The interface can suggest available actions, but that list helps the user. The final decision still happens when the action runs. Otherwise, a new client or a direct Console call would bypass the rule merely by lacking that list.

Render the form and its result in templates/note_preview/index.html.twig:

{% autoescape 'html' %}
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Note transition preview</title>
</head>
<body>
<main>
    <h1>Note transition preview</h1>
    <p>Every check starts from a fresh draft. Nothing is saved or published.</p>

    {{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}
        {{ form_errors(form) }}
        {{ form_row(form.title) }}
        {{ form_row(form.action) }}
        <button type="submit">Check transition</button>
    {{ form_end(form) }}

    {% if result %}
        <section data-state="{{ result.state }}">
            <h2>{{ result.title }}</h2>
            <p>Preview state: {{ result.state }}</p>
        </section>
    {% endif %}
</main>
</body>
</html>
{% endautoescape %}

The novalidate attribute lets this lab show server messages even for an empty field. It does not disable Symfony Validator or CSRF. Normal title rendering through Twig keeps it as text in this HTML context; raw is not needed here.

Console bypasses the form, but not the rule

The second entry point is src/Command/PreviewNoteCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\Application\PreviewNoteTransition;
use App\Application\TransitionAction;
use App\Domain\NoteRuleViolation;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:note:preview', description: 'Check one transition on a fresh teaching draft.')]
final class PreviewNoteCommand extends Command
{
    public function __construct(private readonly PreviewNoteTransition $preview)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('title', InputArgument::REQUIRED, 'Synthetic note title.')
            ->addArgument('action', InputArgument::REQUIRED, 'prepare or publish');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $errorOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
        $action = TransitionAction::tryFrom((string) $input->getArgument('action'));

        if ($action === null) {
            $errorOutput->writeln('Choose prepare or publish.', OutputInterface::OUTPUT_RAW);

            return Command::INVALID;
        }

        try {
            $result = ($this->preview)((string) $input->getArgument('title'), $action);
        } catch (NoteRuleViolation $error) {
            $errorOutput->writeln($error->getMessage(), OutputInterface::OUTPUT_RAW);

            return Command::INVALID;
        }

        $output->writeln(json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), OutputInterface::OUTPUT_RAW);

        return Command::SUCCESS;
    }
}

The command checks whether the action name is recognized. It neither creates a form nor calls its isValid(). The same domain code still rejects an empty title or a disallowed transition.

For this example, success means exit code 0 and JSON on stdout; rejected input or actions mean exit code 2 and an explanation on stderr. Codes and the command mechanism are described in the Console documentation. This is our contract choice, rather than a rule that every programming error should have exit code 2.

Connect and open the example

Add these registrations under the existing services key in config/services.yaml. Preserve earlier services, imports and settings; the fragment below shows additions, rather than a replacement of the whole file.

services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\Application\PreviewNoteTransition: ~
    App\Form\NoteTransitionType: ~
    App\Controller\NotePreviewController: ~
    App\Command\PreviewNoteCommand: ~

Four services enter the container. Form data, the enum and the domain object are created for a particular call; they do not need registration as shared services.

Add config/packages/note_preview.yaml:

framework:
    form: true
    validation: true
    csrf_protection: true
    session: true

twig:
    form_themes: ['form_div_layout.html.twig']

when@test:
    framework:
        session:
            storage_factory_id: session.storage.factory.mock_file

The package and enabling CSRF are documented separately. Our token ID is separate from the typical stateless token IDs, so the form uses a session. This is neither a note store nor permission for a domain action.

Check the configuration and start the local server:

php bin/console lint:yaml config/services.yaml config/packages/note_preview.yaml
php bin/console lint:twig templates/note_preview
php bin/console lint:container
php bin/console debug:router app_note_preview
APP_ENV=dev php -S 127.0.0.1:8000 -t public public/index.php

Open http://127.0.0.1:8000/note-transition-preview. A nonempty title with preparation should produce a ready result. An empty title should produce a field error. A filled title with publication should produce a message that only a prepared note can be published. Each result must be compared with an actual run.

In a second terminal, from the article_demo directory, repeat the same intentions through Console:

APP_ENV=dev php bin/console app:note:preview '  Навчальна нотатка  ' prepare
APP_ENV=dev php bin/console app:note:preview '   ' prepare
APP_ENV=dev php bin/console app:note:preview 'Навчальна нотатка' publish
APP_ENV=dev php bin/console app:note:preview 'Навчальна нотатка' erase

The expected outcomes, in order, are a prepared object, rejection because of the title, rejection because of the state and an unknown action. The form stays out of every case. Stop the local server with Ctrl+C; its purpose and options are described in the PHP manual.

A test that deliberately knows nothing about the form

File tests/Unit/NoteTest.php:

<?php

declare(strict_types=1);

namespace App\Tests\Unit;

use App\Domain\Note;
use App\Domain\NoteRuleViolation;
use PHPUnit\Framework\TestCase;

final class NoteTest extends TestCase
{
    public function testAValidTitleIsNormalizedWithoutAForm(): void
    {
        $note = new Note("  A teaching note\n");

        self::assertSame('A teaching note', $note->title);
        self::assertSame('draft', $note->state());
    }

    public function testAnEmptyTitleIsRejectedWithoutAForm(): void
    {
        $this->expectException(NoteRuleViolation::class);
        $this->expectExceptionMessage('A note title must not be empty.');

        new Note(" \t\n ");
    }

    public function testValidFieldsDoNotAllowSkippingTheReadyState(): void
    {
        $note = new Note('A valid title');

        try {
            $note->publish();
            self::fail('A draft cannot be published directly.');
        } catch (NoteRuleViolation $error) {
            self::assertSame('Only a ready note can be published.', $error->getMessage());
            self::assertSame('draft', $note->state());
        }
    }

    public function testTheAllowedSequenceReachesPublished(): void
    {
        $note = new Note('A valid title');
        $note->prepare();
        $note->publish();

        self::assertSame('published', $note->state());
    }

    public function testPreparingAgainDoesNotRewindTheState(): void
    {
        $note = new Note('A valid title');
        $note->prepare();
        $this->expectException(NoteRuleViolation::class);

        $note->prepare();
    }
}

Run this specific test, whose complete code appears above:

APP_ENV=test php bin/phpunit tests/Unit/NoteTest.php

The test checks the title, a disallowed transition, the unchanged state after rejection and the permitted sequence on one object. It does not prove HTTP, CSRF or message rendering works; those require separate checks of the relevant entry points. Testing levels are described in the Symfony testing documentation.

A useful boundary becomes clear when requirements change. Changing how a field is highlighted changes error presentation. Changing a note’s permitted transition introduces a condition that must apply to the form, Console and any future import. Each entry point can have its own way of helping the user, while the domain rule retains a shared meaning.

  1. Symfony Core Where the controller ends: one use case for creating a note in Symfony
  2. Editorial Draft, review, publication: a state model for one article
  3. Symfony Core Testing a useful feature: from one rule to an HTTP journey

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article