Custom Contao Form Validation & Event Dispatching
How to add cross-field validation to a Contao form and fire a custom event after success, using the core Validator class and EventDispatcher from a self-contained extension.
15 Sept 2025, 23:13 UTC

The problem
You have a Contao form that needs a custom cross-field validation rule—for example, confirming that a password entry matches its confirmation field, or enforcing a business rule that depends on multiple inputs. At the same time, you want a custom event to fire after validation succeeds, so other parts of the extension can react without tight coupling. Contao's FormBuilder supports declarative validators through the Contao\Core\Validator\Validator class, but extending it requires registering the new rule as a service. The contao.system.EventDispatcher lets you hook into core lifecycle events such as postCompile or form-specific events without modifying any core files.
Useful takeaway
By creating a custom validator service and registering it with the contao.validator tag, and wiring an event listener to the EventDispatcher, you can add powerful, cross-field validation to any Contao form while keeping the extension upgrade-safe and fully contained in your own codebase.
Declarative validation with the FormBuilder
Contao forms are defined programmatically or via the Backend UI. Each field can reference a validator class. The core Validator base class provides a validate($value, $parameters) method that returns true on success or an error message on failure. To add a custom rule, you create a subclass, implement the validation logic, and register it as a Symfony service. The FormBuilder discovers validators through the contao.validator service tag (Contao 5) or by class name convention (Contao 4.9). This means the form definition stays clean: you only need to name the validator, and the infrastructure handles the rest.
Hooking into the event dispatcher
After a field passes validation, you may want to trigger additional behavior—such as updating a cache, sending a notification, or logging the action. Instead of calling that logic directly from the form handler, dispatch a custom event. Contao's EventDispatcher implements the PSR-14 pattern: you can listen for a FormValidated event (or any name you choose) and have your listener execute the desired code. Because the dispatcher is registered as a core service, any listener you add in your extension's services.yaml will be invoked automatically when you call dispatch(). This keeps your form code focused on validation and decouples the downstream reaction.
Concrete example: a minimal Contao extension
Suppose you want a form field password_confirm that validates against a password field, and you want a FormValidated event to fire when both are correct.
1. Create the validator class
namespace App\Validator;
use Cont\Core\Validator\Validator;
class PasswordCheckValidator extends Validator
{
public function validate($value, $parameters = []): bool|string
{
$form = $this->getForm();
$password = $form->getValue('password') ?? null;
if ($value !== $password) {
return 'The password and confirmation do not match.';
}
return true;
}
}
2. Register the validator as a service
services:
App\Validator\PasswordCheckValidator:
tags: ['contao.validator']
3. Wire the form field
$form->addPassword('password')
->setLabel('Password');
$form->addPassword('password_confirm')
->setLabel('Confirm password')
->setValidator('App\Validator\PasswordCheckValidator');
4. Create an event listener
namespace App\Listener;
use Contao\System\EventDispatcher;
use Contao\Event\Event;
class FormValidationListener
{
public function onFormValidated(Event $event): void
{
// Custom reaction – e.g., log, cache update, notification
}
}
5. Register the listener
services:
App\Listener\FormValidationListener:
tags:
- { name: contao.event_listener, method: onFormValidated }
Verification checklist
- Install the extension with
php contao:console extension:install custom_form_validation. - Open the Contao Backend, create a form, add the two password fields and assign the validator.
- Submit the form with matching values – it should accept.
- Submit with mismatched values – a validation error appears.
- Check the Contao log or add a temporary
debug()call inonFormValidatedto confirm the event fired. - If the event does not fire, verify that
dispatch('FormValidated')is called somewhere in the form's submit handler, or that the listener tag matches the dispatcher's expected format for your Contao version.
Trade-offs and upgrade safety
Pros: No core files are modified; the validator leverages Contao's existing infrastructure; the event dispatcher pattern is stable across 4.9 and 5.0 bug-fix releases, but event names or tag formats can change between major versions.
Cons: A custom validator that isn't registered as a service will silently fail – the FormBuilder will not apply the rule, and no error will be raised. Similarly, if the event listener tag does not match the dispatcher's expectations, the listener never fires.
Practical verification: After installing the extension, run php contao:console debug:extension custom_form_validation (or inspect the extension's composer.json autoload) to confirm the services are loaded. Create a test form and deliberately trigger both valid and invalid submissions. Use the Backend's Performance → Log panel to see validator errors and event dispatch entries.
Actionable closing
To add custom validation and event handling to your next Contao form:
- Write a validator class that extends
Contao\Core\Validator\Validator. - Register it with the
contao.validatorservice tag. - Reference the validator class from your form field configuration.
- Create an event listener tagged for the Contao EventDispatcher and call
dispatch('YourEventName')after successful validation. - Test with matching and mismatched inputs, and confirm the listener runs via the log or a debug statement.
This pattern keeps your extension self-contained, upgrade-safe, and fully leverages Contao's built-in validation and event infrastructure.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.