AssociativeValidator / ObjectValidator currently handle undeclared input keys two ways: stripped from the output (default), or copied through unvalidated (passthrough()). There's no way to make an undeclared key a validation error.
Use case
Validating a hand-authored config file — a typo like auto_updat => true should fail loudly pointing at the bad key, not be silently dropped and leave the setting at its default. The same need comes up for strict API request validation where unexpected fields should be rejected rather than ignored.
Proposed
A strict() (or noUnknownKeys()) method on the schema validators that emits a ValidationError for each key not in the schema:
- path = the offending key
- a stable code (e.g.
ValidationCode::UnrecognizedKey)
- aggregated with other field errors like the rest of schema validation
Prior art
| Library |
strip |
keep |
reject |
| Zod |
.strip() (default) |
.passthrough() |
.strict() |
| Yup |
— |
default |
.noUnknown() |
| JSON Schema |
— |
default |
additionalProperties: false |
| Lemmon today |
default |
passthrough() |
missing |
Workaround until then
array_diff(array_keys($input), $allowedKeys) before handing the array to the validator.
AssociativeValidator/ObjectValidatorcurrently handle undeclared input keys two ways: stripped from the output (default), or copied through unvalidated (passthrough()). There's no way to make an undeclared key a validation error.Use case
Validating a hand-authored config file — a typo like
auto_updat => trueshould fail loudly pointing at the bad key, not be silently dropped and leave the setting at its default. The same need comes up for strict API request validation where unexpected fields should be rejected rather than ignored.Proposed
A
strict()(ornoUnknownKeys()) method on the schema validators that emits aValidationErrorfor each key not in the schema:ValidationCode::UnrecognizedKey)Prior art
.strip()(default).passthrough().strict().noUnknown()additionalProperties: falsepassthrough()Workaround until then
array_diff(array_keys($input), $allowedKeys)before handing the array to the validator.