Writing a validator
The readers clean one value at a time and answer with the value, or with the honest nothing.
A form, an import or an API endpoint wants something else first: every problem with the whole
payload, at once, in words a person can act on. That is what Explain is for, and this page
builds a validator out of it — a method that takes the bag a payload arrived in and hands back
each field's reason.
You need Your first payload behind you: the bag, the readers, and why nothing throws.
The shape of a validator
Three moves, in order:
- What must be there at all.
CkDictionary::MissingKeysanswers the required keys that are absent — present-but-blank does not count as missing, the next move judges that. - Each value, judged by the class that owns it. Every class with a reader has an
Explain:CkEmail::Explain($value),CkMoney::Explain($value), and where a class has several readers,CkUS::Explain($value, 'Zip'). It answers''when the value passes and the reader's own reason otherwise — the same wordsthrowIfInvalid: truewould put in the exception — and it never throws, not even with the throw switch on. - Rules between fields. The validators do those:
CkDate::IsBeforefor a start and an end date,CkDate::IsAdultfor a birth date,CkIntl::PostalCodewith the country beside it.
The result is an array, field name to reason, empty when the payload is good.
The payload
The signup we will judge, as it came off the wire:
use SafeCoder\CommonKit\CkPayload;
$body = '{
"name": " ",
"email": "mary.smith.gmail.com",
"country": "CA",
"postalCode": "1234",
"birthDate": "5/6/26",
"amount": "ten"
}';
$payload = CkPayload::FromJson($body);
Five of the six fields are wrong, each in its own way, and one is missing outright: there is no
phone. A reader would reject them one call at a time. The validator says all of it in one
answer.
The validator
use SafeCoder\CommonKit\CkCountry;
use SafeCoder\CommonKit\CkDate;
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkIntl;
use SafeCoder\CommonKit\CkMoney;
use SafeCoder\CommonKit\CkText;
use SafeCoder\CommonKit\CkUS;
final class SignupValidator
{
/**
* @param array<array-key, mixed> $payload The bag the payload arrived in.
* @return array<string, string> Field name to reason; empty when the payload is good.
*/
public static function Validate(array $payload): array
{
$problems = [];
// a field is reported once: a missing key stays "required", a present value gets its reason
$judge = static function (string $key, string $reason) use (&$problems): void {
if ($reason !== '' && isset($problems[$key]) === false) {
$problems[$key] = $reason;
}
};
// 1. what must be there at all
foreach (CkDictionary::MissingKeys($payload, 'name', 'email', 'country', 'postalCode', 'birthDate', 'amount', 'phone') as $key) {
$problems[$key] = 'required';
}
// 2. each value, judged by the class that owns it
$judge('name', CkText::Explain(self::Text($payload, 'name')));
$judge('email', CkEmail::Explain(self::Text($payload, 'email')));
$judge('country', CkCountry::Explain(self::Text($payload, 'country')));
$judge('phone', CkUS::Explain(
input: self::Text($payload, 'phone'),
what: 'Phone'
));
$judge('birthDate', CkDate::Explain(CkDictionary::Value(
dictionary: $payload,
key: 'birthDate'
)));
$judge('amount', CkMoney::Explain(CkDictionary::Value(
dictionary: $payload,
key: 'amount'
)));
// 3. rules between fields: a postal code is only judged against a country that passed
if (isset($problems['country']) === false) {
$judge('postalCode', CkIntl::Explain(
input: self::Text($payload, 'postalCode'),
what: 'PostalCode',
country: self::Text($payload, 'country')
));
}
if (isset($problems['birthDate']) === false
&& CkDate::IsAdult(CkDictionary::Value(dictionary: $payload, key: 'birthDate')) === false) {
$problems['birthDate'] = 'must be 18 or older';
}
return $problems;
}
/**
* The raw text of a field — a number in the JSON becomes its digits, a missing field ''.
*
* @param array<array-key, mixed> $payload
*/
private static function Text(array $payload, string $key): string
{
return CkDictionary::String(
dictionary: $payload,
key: $key
);
}
}
Read it with the three moves in mind:
MissingKeysfirst, so an absent field says "required" rather than the "no value" a reader would say about it.$judgekeeps the first reason a field gets, which is why the order matters.- Text readers take text, value readers take the value.
CkText,CkEmail,CkCountry,CkUSandCkIntljudge text, soTextpulls the field out withCkDictionary::String— a number in the JSON becomes its digits, a missing or null field becomes'', whichExplaincalls "no value".CkDate,CkMoneyandCkNumberjudge a value of any kind, so they takeCkDictionary::Valueas it is: a JSON number stays a number and a date object stays a date object. - A dependent check waits for its input to pass. The postal code is judged against the country only when the country itself passed, or the reason would be about the country twice. Same for the age rule.
What it answers
// no-check
$problems = SignupValidator::Validate($payload);
For the payload above, every problem at once:
// no-check
[
'phone' => 'required',
'name' => 'no value',
'email' => 'no @ in the value',
'birthDate' => 'a two-digit year is ambiguous',
'amount' => 'letters in the amount',
'postalCode' => 'not the shape of a postal code of Canada',
]
Each reason is the reader's own — the same words CkEmail::Address($value, throwIfInvalid: true)
would carry — so the message beside the field and the exception in the log never disagree.
Using it at the gate
In a plain PHP handler the array is the whole 400 response.
CkRequest::Bag()->Body() is the body of the current request as
the bag, read by its content type — Using it with Laravel, Joomla! and
WordPress show each framework's own way in:
// no-check
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkIntl;
use SafeCoder\CommonKit\CkRequest;
$payload = CkRequest::Bag()->Body();
$problems = SignupValidator::Validate($payload);
if ($problems !== []) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode($problems);
exit;
}
// past the gate the readers cannot reject: the validator judged by their rules
$email = CkEmail::Address(CkDictionary::String(dictionary: $payload, key: 'email'));
$postalCode = CkIntl::PostalCode(
input: CkDictionary::String(dictionary: $payload, key: 'postalCode'),
country: CkDictionary::String(dictionary: $payload, key: 'country')
);
That last comment is the point of the design. Explain and the reader share one set of rules,
so once the validator says nothing is wrong, reading the values is a formality — no second
round of checks, no try/catch, no fallback that quietly hides a bad row.
Optional fields
A field that may be absent is judged only when it is there:
// no-check
if (CkDictionary::Has(dictionary: $payload, key: 'note')) {
$judge('note', CkText::Explain(self::Text($payload, 'note')));
}
Has answers whether the key exists at all, a JSON null
included; a present-but-null note then says "no value", which is what you want when the client
sent the key on purpose.
Why not throwIfInvalid
throwIfInvalid: true is right when one bad value should stop everything: an import, a test, a
job that must not continue. It stops at the first problem, by design. A validator wants the
opposite — every problem, and no exception in the flow of an ordinary request — which is why it
is built on Explain and the validators, none of which throw.
Keep one validator per payload
Put the field list in one place and test it with a bad payload:
public function testValidateSaysEverythingAtOnce(): void
{
$payload = CkPayload::FromJson('{ "email": "junk", "country": "Atlantis" }');
$problems = SignupValidator::Validate($payload);
self::assertSame('no @ in the value', $problems['email']);
self::assertSame('not a recognised country or code', $problems['country']);
self::assertSame('required', $problems['name']);
self::assertArrayNotHasKey('postalCode', $problems); // not judged: the country failed
}
The readers downstream then need no field knowledge of their own — they read what the validator let through.
Where next
- Your first payload — a fifteen-minute tutorial: a messy order payload to clean, typed values, and the whole handler at the end.
- Common mistakes — the traps everyone hits once with the library itself.
- Using it with a framework — Laravel, Joomla! and WordPress: the way in, reading the request, validating, one
ToNullon the way to the database, and where the files go. - CkDictionary —
Value,String,HasandMissingKeys, and the dotted paths every reader takes.