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
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
Comment #2
mglamanComment #3
d34dman commentedFlowDrop 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
AllowedValuesnext. 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.Comment #5
mukesh-kumar3 commentedI 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
JsonSchemaConstraintInterface, following the proposal in the issue summary, so supported core and contributed constraints can describe their JSON Schema keywords.Lengthconstraint as an initial step, supporting representable minimum and maximum string lengths.For example, a required string with
Length: {max: 3}would produce: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
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.
Comment #7
mukesh-kumar3 commentedMR !18061
provides an initial Length-only implementation for review.
Implementation includes:
JsonSchemaConstraintInterface.minLengthandmaxLengthgeneration.Constraint discovery currently uses
TypedDataInterface::getConstraints().Local verification passed:
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.
Comment #8
mukesh-kumar3 commentedInvestigated the PHP 8.6 warning jobs. Both inspected logs report
the same deprecation in
mikey179/vfsstream:vfsStreamFile.php:374callsspl_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.
Comment #9
mglamanThanks for picking this up. The
Lengthconstraint 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.Comment #10
mukesh-kumar3 commentedThanks 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.
Comment #11
mukesh-kumar3 commentedComment #12
mglamanI left notes on the MR for the changes in #10. Setting to Needs work for those.
Also needed:
main. UseisNullable()from #3627331 inPrimitiveDataNormalizer.JsonSchemaConstraintInterfaceand the new keywords in the schema output.Regexto #3643475 andCountto #3643476, replaceformat: emailwith theidn-emailschema, and remove the open questions that are settled.Generated with the help of an LLM.
Comment #14
mukesh-kumar3 commentedPosted the updated summary here by mistake. I’m moving it to the Issue summary field.
Comment #15
mukesh-kumar3 commentedUpdated 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.
Comment #16
mukesh-kumar3 commentedComment #18
mglamanLooks good to me. I added a paragraph to the change record about subclasses inheriting
getJsonSchemaKeywords().Comment #19
fagoThanks 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:
Lengthwithmax: 3returnsmaxLength: 3. The schema says everything.Rangewith a property-path bound returns only the static bound.AllowedValueswith a callback returns[]. The value looks unconstrained, but it is not.Emailreturns 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
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-emailA format is only helpful if every validator gives the same verdict.
idn-emailneeds 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:
Emailalready declaresformat: emailthere, and #3643896: Email data type JSON Schema excludes values accepted by Drupal validation is the place to decide whether that stays.The pattern is deliberately loose and needs a test against the Email validator, so it never rejects an accepted value.
Emailthen 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).
Comment #20
michaellander commentedHere 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.
Comment #21
mglamanI'm replacing
format: idn-emailwith thepatternfrom #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 anenumafter 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?
Comment #22
mglamanComment #23
mukesh-kumar3 commentedThanks for the update. Pulled commit
2ac710fc5edand verified locally on PHP 8.5.13: