Problem/Motivation

The JsonSchema attribute describes the normalized representation of typed data, but schema generation does not yet include the restrictions expressed by its validation constraints. A schema consumer can therefore accept input that Drupal subsequently rejects.

For example, a string constrained to the currency codes USD and CAD with a maximum length of three is described only as a string. This issue adds supported validation metadata to primitive-data schemas, building on the existing serializer JSON Schema support.

Steps to reproduce

use Drupal\Core\TypedData\DataDefinition;

$definition = DataDefinition::create('string')
  ->setRequired(TRUE)
  ->addConstraint('AllowedValues', ['choices' => ['USD', 'CAD']])
  ->addConstraint('Length', ['max' => 3]);

$data = \Drupal::typedDataManager()->create($definition);
$schema = \Drupal::service('serializer')->getJsonSchema($data, []);

Before this change:

['type' => 'string']

Expected with the implementation in this issue:

[
  'type' => 'string',
  'enum' => ['USD', 'CAD'],
  'maxLength' => 3,
]

Proposed resolution

MR !18061 adds Drupal\Core\Serialization\JsonSchemaConstraintInterface with the following method:

public function getJsonSchemaKeywords(): array;

The interface requires that returned keywords do not reject values accepted by the constraint. A less restrictive representation is allowed. Unsupported options produce no keywords, or only the independently representable part of the restriction.

Constraint Implemented representation
Length minLength and maxLength for non-negative integer limits using UTF-8 Unicode code-point counting without a normalization callback.
Range minimum and maximum for finite integer or float bounds. Each static bound is exported independently; property-path bounds are omitted.
AllowedValues enum for non-empty static choices for a single value. Callback-based choices, multiple selections, and match: FALSE produce no enum keywords.
Email anyOf with an empty-string alternative and a pattern that requires one @, when no normalizer callback is configured and the constraint uses strict mode.

The Email constraint contributes this schema fragment:

{
  "anyOf": [
    {"const": ""},
    {"pattern": "^[^@]+@[^@]+$"}
  ]
}

SchematicNormalizerHelperTrait::addConstraintKeywords() accepts a DataDefinitionInterface. It obtains configured and default constraint options through getConstraints() and creates constraint instances through getValidationConstraintManager()->create().

The helper casts raw enum choices to the normalized type of the relevant schema branch, removes duplicates, and omits unsupported representations. Constraint keywords are applied to non-null schema alternatives. Overlapping keywords are retained using allOf, preserving the existing restrictions.

PrimitiveDataNormalizer uses the helper and preserves main's isNullable() handling. Normalizers that change the representation, such as timestamp normalizers, retain their existing schema-generation paths. This issue does not add constraint discovery to every normalizer.

The Email data type's existing format: email attribute remains unchanged. Its compatibility with accepted empty and international values is covered by a separate follow-up. Adding a constraint's anyOf does not relax an existing sibling format keyword.

Test coverage and verification

Kernel schema checks use one test method and a data provider supplying the data definition and expected schema. Coverage includes required and nullable values, zero bounds, enum casting and deduplication, negated choices, default Email constraints, and overlapping length restrictions. The callback test remains separate because its closure cannot be serialized in a separate-process data set. Schema tests do not repeat constraint-validator assertions.

A StringData fixture declares maxLength: 10 on getCastedValue(). Combining it with Length max: 3 verifies the allOf branch for both required and optional strings. Focused Range unit tests verify that a static bound remains available when the opposite bound uses property-path metadata.

  • Local unit verification after the main merge: 188 tests, 549 assertions passed.
  • Local constraint kernel verification after the main merge: 31 tests, 31 assertions passed.
  • Local PHPCS, PHPStan, and whitespace checks passed. The subsequent ShareEnvironment declaration is covered by the latest CI pipeline.
  • Pipeline #1080413 completed with warnings from allowed-to-fail unit jobs. Composer, spell-checking, PHPCS, PHPStan, Kernel, Functional, Functional JavaScript, Build, and Nightwatch checks passed.

Separate follow-up issues

  • #3643475: Regex constraint mapping and safe PCRE-to-ECMA-262 conversion.
  • #3643476: Count constraint mapping to list-schema keywords; depends on #3627328.
  • #3643896: Email data-type schema compatibility with values accepted by Drupal validation.

Remaining tasks

  • Review the implementation, regression coverage, and draft change record.
  • Address any further maintainer feedback and confirm the appropriate release metadata.

User interface changes

None.

Introduced terminology

None.

API changes

A new optional Drupal\Core\Serialization\JsonSchemaConstraintInterface allows core, contributed, and custom constraints to supply JSON Schema keywords. Callers cast enum values to the applicable normalized type. Generated primitive-data schemas gain supported validation keywords; normalized payloads are unchanged.

Draft change record: Validation constraints can contribute JSON Schema keywords.

Data model changes

None.

Release notes snippet

Serializer-generated primitive-data JSON Schemas can include supported Length, Range, static AllowedValues, and Email constraint metadata. Custom constraints can opt in through JsonSchemaConstraintInterface.


AI assistance: ChatGPT assisted with drafting of this updated summary.

Issue fork drupal-3627330

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

mglaman created an issue. See original summary.

mglaman’s picture

Issue tags: +rosetta
d34dman’s picture

FlowDrop would use this directly. Our tool schemas carry no enum, min/max or pattern today, so the workflow editor, or an agent building a workflow, only learns about a limit when Tool API rejects the call. The #3635315: [Prototype] Write a setting's rules once, in config schema, and use them for validation, forms and the published JSON Schema prototype covers Length, Range and Count via $object->getConstraints().

Two suggestions:

1. Read the constraints from the definition instead. DataDefinition::getConstraints() already adds the type's defaults, so #3638400: Generate JSON Schema from a data definition, without a data object can reuse it.

2. Settle AllowedValues next. Choices that come from a callback can depend on the user or on other values, so they should be evaluated when the schema is built, or left out, never published as a fixed enum.

mukesh-kumar3 made their first commit to this issue’s fork.

mukesh-kumar3’s picture

I would like to work on this issue. Before starting implementation, I would appreciate feedback on the proposed approach and initial scope.

My understanding is that validation constraints should contribute JSON Schema keywords when those keywords accurately describe the normalizer's output.

Proposed approach

  1. Introduce an optional JsonSchemaConstraintInterface, following the proposal in the issue summary, so supported core and contributed constraints can describe their JSON Schema keywords.
  2. Implement the interface for the Length constraint as an initial step, supporting representable minimum and maximum string lengths.
  3. Read constraint configuration from the data definition and resolve constraint objects through the constraint manager, without creating a typed-data object solely for schema generation.
  4. Integrate the keywords into the applicable string schema. For nullable values, apply length restrictions to the string branch while preserving the null branch.
  5. Preserve the existing schema when a constraint or its options cannot be represented accurately.

For example, a required string with Length: {max: 3} would produce:

{
  "type": "string",
  "maxLength": 3
}

Normalization considerations

I propose initially applying this to normalizers whose output remains a string. Normalizers that transform the representation need separate consideration: for example, a timestamp's stored value is numeric, while its normalized output is a datetime string.

Proposed test coverage

  • Minimum, maximum, and exact string lengths, including zero.
  • Required and optional string definitions.
  • Preservation of existing schema keywords and nullability.
  • Unicode length semantics and unsupported constraint options.
  • Unchanged behavior for unsupported constraints.

Would a Length-first implementation be a suitable starting point, with the remaining constraints added in subsequent steps? Feedback on the interface's namespace, method contract, and the appropriate integration point would help establish the direction before implementation.

mukesh-kumar3’s picture

Status: Active » Needs review

MR !18061
provides an initial Length-only implementation for review.

Implementation includes:

  • Added JsonSchemaConstraintInterface.
  • Supported minLength and maxLength generation.
  • Preserved nullable-string handling.
  • Added tests for Unicode, zero limits, and unsupported options.

Constraint discovery currently uses
TypedDataInterface::getConstraints().

Local verification passed:

  • Serialization unit suite: 143 tests, 480 assertions.
  • Constraint kernel tests: 8 tests, 16 assertions.
  • PHPCS, PHPStan, and git diff --check.

Pipeline #1077396
passed spelling, PHPCS, PHPStan, Composer, Kernel, Functional,
Functional JavaScript, Build, and Nightwatch checks.
Its overall status is Warning; Unit Core and Component
warning jobs remain to be investigated.

Requesting feedback on the interface, integration approach, and
Length-first scope. Other constraint mappings remain outstanding.

mukesh-kumar3’s picture

Investigated the PHP 8.6 warning jobs. Both inspected logs report
the same deprecation in mikey179/vfsstream:
vfsStreamFile.php:374 calls
spl_object_hash(), deprecated since PHP 8.6.
The jobs are allowed to fail. These excerpts do not identify a failure
in the JSON Schema implementation.

mglaman’s picture

Status: Needs review » Needs work

Thanks for picking this up. The Length constraint is a good first use case. I left notes on the MR for the interface contract, where to read constraints from, and which constraints to add next.

mukesh-kumar3’s picture

Thanks for the review. I’ll document the interface’s acceptance rule, refactor constraint discovery to use DataDefinitionInterface, and apply keywords to non-null schema branches while retaining the allOf handling. I’ll also add Range, Email, and static AllowedValues support with tests, and open separate follow-up issues for Regex and Count.

mukesh-kumar3’s picture

Status: Needs work » Needs review
mglaman’s picture

Status: Needs review » Needs work

I left notes on the MR for the changes in #10. Setting to Needs work for those.

Also needed:

  1. Rebase the MR on main. Use isNullable() from #3627331 in PrimitiveDataNormalizer.
  2. Add a change record for JsonSchemaConstraintInterface and the new keywords in the schema output.
  3. Update the issue summary. Move Regex to #3643475 and Count to #3643476, replace format: email with the idn-email schema, and remove the open questions that are settled.

Generated with the help of an LLM.

mukesh-kumar3 changed the visibility of the branch 3627330-validation-constraints-do to hidden.

mukesh-kumar3’s picture

Posted the updated summary here by mistake. I’m moving it to the Issue summary field.

mukesh-kumar3’s picture

Issue summary: View changes

Updated the issue summary to reflect the implementation and review feedback. Added the draft change record (#3643929), linked the Regex, Count, and Email follow-ups, and updated the test and CI results.

mukesh-kumar3’s picture

Status: Needs work » Needs review

mukesh-kumar3 changed the visibility of the branch 3627330-validation-constraints-do to active.

mglaman’s picture

fago’s picture

Status: Reviewed & tested by the community » Needs review

Thanks for this. The per-constraint interface is the right shape, and "keywords must not reject values the constraint accepts" matches my plans for portable-schema very well. Two points before contrib starts implementing it.

1. A constraint cannot say whether its json-schema mapping is complete

When a schema says nothing about a rule, that currently has two meanings: "there is no rule" and "there is a rule the schema cannot express". A caller cannot tell them apart:

  • Length with max: 3 returns maxLength: 3. The schema says everything.
  • Range with a property-path bound returns only the static bound.
  • AllowedValues with a callback returns []. The value looks unconstrained, but it is not.
  • Email returns keywords, but the validator checks more than they say.

I think as soon as a constraint implements the interface, we should be able to know whether we have a complete mapping for a certain case, or not. So I think this needs work for AllowedValues.

Proposal: add for example

public function isJsonSchemaComplete(): bool;

or return a small value object with the keywords and that flag. A constraint without the interface is incomplete by definition.

2. Email: I would not emit format: idn-email

A format is only helpful if every validator gives the same verdict. idn-email needs IDNA processing, which PHP and JavaScript implementations do differently, where they implement the format at all. So a client's validator can reject an address Drupal accepts - this goes against the rule defined by the interface.

Suggestion:

  • Leave the format to the data type. Email already declares format: email there, and #3643896: Email data type JSON Schema excludes values accepted by Drupal validation is the place to decide whether that stays.
  • Let the constraint add only what every validator evaluates the same way:
    {"anyOf": [{"const": ""}, {"pattern": "^[^@]+@[^@]+$"}]}

    The pattern is deliberately loose and needs a test against the Email validator, so it never rejects an accepted value.

  • Email then reports its keywords as incomplete, per point 1.

So setting back to needs-review to get some more input on this before we move on!

AI disclosure: I created and steered this comment with Claude Code (Fable 5.2).

michaellander’s picture

Here are all the ones covered by the Tool API normalizer:
https://git.drupalcode.org/project/tool/-/blob/1.0.x/src/Normalizer/Inpu...

I actually think it's more appropriate to leave 'callback' based AllowedValues/Choices out, as you have, to avoid overloading, but it may be worth considering some of the other mappings we have.

We also set a strict enum limit, though this is a bit arbitrary, and harder to make a case for core.

mglaman’s picture

I'm replacing format: idn-email with the pattern from #18 in the MR, with a test against the Email validator.

I'd move isJsonSchemaComplete() to a new issue. It's an awkward flag to put on the constraint. getJsonSchema() returns an array, so a caller has no way to read it. The normalizer can also drop an enum after the constraint returns it, so the constraint can't always know the answer.

If a caller needs to know that a rule is missing, I think the schema itself should say so, like with an annotation. We can add that later without changing this interface. What would portable-schema do differently when a schema is incomplete?

mglaman’s picture

Issue summary: View changes
mukesh-kumar3’s picture

Thanks for the update. Pulled commit 2ac710fc5ed and verified locally on PHP 8.5.13:

  • EmailConstraintJsonSchemaTest: 10 tests, 20 assertions passed.
  • JsonSchemaConstraintTest: 31 tests, 31 assertions passed.