Drupalwoo ☉

How to use Drupal’s Typed Data API for complex validation

Drupal’s Typed Data API provides a consistent way to describe values, organise nested structures, and apply validation rules before data reaches storage or business logic. It is useful when a value is more complicated than a single text field, such as an address object, a product configuration, an API payload, or a collection of repeatable items.

The API connects data definitions with Drupal’s validation system. A definition can describe a scalar value, a map of named properties, or a sequence of items. Constraints can then check required values, string lengths, numeric ranges, formats, and custom business rules. Validation returns structured violations instead of forcing every caller to interpret a boolean result.

This approach is particularly helpful for Drupal projects that receive data from several sources. A submitted form, JSON request, migration row, and administrative interface can all pass through the same typed structure. For an Australian site, that might mean validating a delivery address with a suburb, state, postcode, and Australian phone number consistently across a commerce workflow.

Understand the typed data model

Typed data is Drupal’s metadata layer for values. A definition tells Drupal what kind of data exists and what rules apply to it, while a typed data object holds the actual value. Common primitive types include string, integer, float, boolean, and uri. Complex types include maps with named properties and sequences containing multiple items.

A map is appropriate when each property has a known name. An address could contain street, suburb, state, and postcode. A sequence is better for a repeatable list, such as several delivery addresses or line items. Complex structures can combine both: a sequence of maps, where every map represents one item.

The definition and the value should be kept conceptually separate. The definition is reusable metadata, while the value may change for every request. This makes it possible to validate the same structure in a controller, a custom service, a queue worker, or a migration process.

Typed data is also different from entity field storage. Entity fields already expose typed data through field definitions, and Drupal validates many field constraints automatically. The standalone Typed Data API is useful when the structure does not belong directly to an entity, or when an application needs validation before an entity is created or updated.

Build a nested definition

Drupal’s typed data manager can create data objects from definitions. A simple nested definition can be assembled with MapDataDefinition, SequenceDataDefinition, and DataDefinition. The following example describes a delivery request containing customer details and multiple Australian addresses:

use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\MapDataDefinition;
use Drupal\Core\TypedData\SequenceDataDefinition;

$address_definition = MapDataDefinition::create()
  ->setPropertyDefinition('street', DataDefinition::create('string'))
  ->setPropertyDefinition('suburb', DataDefinition::create('string'))
  ->setPropertyDefinition('state', DataDefinition::create('string'))
  ->setPropertyDefinition('postcode', DataDefinition::create('string'));

$addresses_definition = SequenceDataDefinition::create()
  ->setItemDefinition($address_definition);

$request_definition = MapDataDefinition::create()
  ->setPropertyDefinition(
    'customer_name',
    DataDefinition::create('string')
  )
  ->setPropertyDefinition('addresses', $addresses_definition);

Definitions can carry constraints directly. A postcode should remain a string because leading zeroes matter, especially for locations such as parts of New South Wales and Victoria. Treating it as an integer could turn 0800 into 800 and destroy meaningful input.

$postcode_definition = DataDefinition::create('string')
  ->setRequired(TRUE)
  ->addConstraint('Length', ['min' => 4, 'max' => 4])
  ->addConstraint('Regex', [
    'pattern' => '/^[0-9]{4}$/',
  ]);

The postcode definition can then be assigned to the postcode property. In a real application, state validation could also use a custom constraint to allow only ACT, NSW, NT, QLD, SA, TAS, VIC, or WA. That is more reliable than checking a value informally in a controller.

When definitions become large, place construction in a dedicated factory or service. A reusable service makes the schema easier to test and avoids copying slightly different rules into several forms and controllers.

Add constraints at the right level

Constraints should be attached as close as possible to the rule they describe. A Length constraint belongs on a string property, while a collection-size constraint belongs on the sequence. Rules involving several sibling properties belong on the map or on a custom constraint that receives the complete structure.

Drupal supports core Symfony Validator constraints through typed data. Common examples include NotBlank, Length, Range, Regex, Email, and Choice. The exact constraint options should be checked against the Drupal version used by the project, since supported options and validation behaviour can vary between releases.

$customer_definition = MapDataDefinition::create()
  ->setPropertyDefinition(
    'email',
    DataDefinition::create('string')
      ->setRequired(TRUE)
      ->addConstraint('Email')
  )
  ->setPropertyDefinition(
    'phone',
    DataDefinition::create('string')
      ->addConstraint('Regex', [
        'pattern' => '/^(?:\+61|0)[2-478](?:[ -]?[0-9]){8}$/',
      ])
  );

A phone expression should be treated as a project-specific policy rather than a universal representation of every Australian number. A site serving customers in Perth, Hobart, or regional Queensland may need to accept different formatting conventions. It is often sensible to normalise whitespace and punctuation before validation, while retaining the original value for display if required.

Cross-property rules are where custom constraints become valuable. For example, a delivery address could require a postcode that matches the selected state, or a request could require either an email address or a mobile number. A custom constraint can inspect the map and add a violation to the relevant property path.

Create values and inspect violations

Once the definition is ready, obtain Drupal’s typed data manager and create a typed value. In dependency-injected code, inject typed_data_manager rather than calling the global service directly.

$typed_data_manager = $container->get('typed_data_manager');

$value = [
  'customer_name' => 'Morgan Lee',
  'addresses' => [
    [
      'street' => '14 King Street',
      'suburb' => 'Newtown',
      'state' => 'NSW',
      'postcode' => '2042',
    ],
  ],
];

$typed_data = $typed_data_manager->create(
  $request_definition,
  $value
);

$violations = $typed_data->validate();

The result is a ConstraintViolationListInterface. An empty list means the structure passed its configured constraints. Each violation contains a message, a property path, a constraint code, and contextual information that can be used by a form or API response.

if ($violations->count()) {
  foreach ($violations as $violation) {
    $path = $violation->getPropertyPath();
    $message = $violation->getMessage();

    // Log, display, or serialise the error.
  }
}

For a sequence of addresses, a path might identify a particular item and property, such as addresses.0.postcode. Avoid converting all errors into one generic message. An editor in a Melbourne office needs to know which repeated item failed, while an API consumer needs a stable path it can map back to its request payload.

Validation should happen before side effects. Check the structure before creating entities, sending notifications, charging a card, or placing a record on a queue. Sanitisation and normalisation still have a role, but they should not silently hide invalid input or replace validation rules.

Select the appropriate validation layer

Typed Data API validation works best when each layer has a clear responsibility. A form can provide immediate user feedback, a typed definition can protect an application service, and entity constraints can enforce rules at the storage boundary. Repeating a rule may be justified when data can enter through multiple paths, but the messages and definitions should remain consistent.

Validation approach Best use Strength Limitation
Form API validation Interactive Drupal forms Clear field-level feedback Does not protect non-form input
Entity and field constraints Content and configuration entities Integrates with Drupal storage Less convenient for temporary payloads
Typed Data API Nested service or API structures Reusable, structured violations Requires explicit definition setup
Custom Symfony constraint Cross-property or domain rules Expresses complex business logic Needs tests and maintenance
JSON Schema or external validation Public API contracts Useful for outside consumers Does not replace Drupal-side checks

A JSON API endpoint might receive a payload that looks valid according to its external schema but still violates a Drupal business rule. Typed data can validate the internal representation after decoding JSON. Conversely, if other systems consume the endpoint, publishing a JSON Schema may be useful alongside the Drupal implementation.

Configuration schema deserves separate attention. Drupal configuration schema describes configuration data for translation, inspection, and typed handling, but it is not a drop-in replacement for all runtime validation. A configuration value can have a declared type and still need constraints when it is submitted or used.

For an Australian organisation, this separation is practical when the same workflow is used by a local admin team and a national integration. A form might show friendly state labels, while an API accepts machine names. The typed structure can provide the stable internal contract between those interfaces.

Test and maintain complex validation

Complex definitions need tests for both valid and invalid structures. Test a complete valid value, missing required properties, malformed nested items, empty sequences, unexpected states, invalid postcodes, and cross-property failures. Include boundary cases such as a four-digit postcode beginning with zero and an address from a remote region.

Use kernel tests when Drupal services, plugins, entity definitions, or custom constraints are involved. Unit tests can be enough for a pure constraint class if its dependencies are injected cleanly. Assertions should check the number of violations and their property paths, rather than relying only on translated message text.

A practical maintenance routine includes:

Documentation is part of the contract. Record whether states use abbreviations, whether postcodes are strings, which phone formats are accepted, and whether blank optional properties are omitted or represented as empty values. This prevents a later developer from “cleaning up” a valid 0800 postcode or rejecting a regional address because it does not match assumptions based on Sydney data.

For developers who regularly work across Drupal builds, Abhaya Chauhan provides useful broader technical context, while a project-specific implementation should still follow the APIs and coding standards of its installed Drupal version. Keeping validation definitions version-aware is especially important when upgrading core or changing contrib modules.

Apply the pattern in Drupal projects

A well-designed typed structure creates a boundary around unreliable input. Decode the request, normalise only what the application has explicitly decided to normalise, create the typed value, validate it, and then pass the trusted representation to the next service. This sequence is easier to reason about than scattered checks across controllers and form submit handlers.

The pattern also supports gradual growth. Start with a map containing a few scalar values, then introduce nested maps or sequences when the domain requires them. Add a custom constraint when a rule cannot be expressed clearly with a core constraint. Avoid making every possible rule part of one enormous definition, because smaller definitions are easier to reuse and test.

When reviewing implementation examples and Drupal administration guidance, the Drupalwoo about page describes the practical focus of a site built around Drupal development and website administration. That perspective suits Typed Data work well: the goal is a maintainable implementation that helps developers and site editors handle real data safely.

Typed Data API validation is most effective when it becomes a shared application contract rather than a last-minute check. Clear definitions, precise constraints, meaningful violation paths, and focused tests allow complex Drupal structures to remain predictable as forms, integrations, and editorial workflows evolve.