Programming · free software · the open webSubscribe via RSS

Can You Build a Tiny Protocol Message Validator?

From the earlier reference collection. Read the current software blog.

A lightweight validator can check a message against an explicit schema and return actionable, field-specific diagnostics.

Write down the message contract

A protocol validator is only as precise as the contract it checks. Define the expected fields, their types, whether they are required, and any simple constraints such as an allowed range or a string length. Keep the schema small enough that a user can understand why each rule exists.

For example, a reading message might require a string sensor_id, a numeric value, and a timestamp string. Decide whether additional fields are allowed. Strict rejection catches typos early, while allowing unknown fields can make versioned messages easier to extend. The right choice depends on the protocol’s compatibility rules, so state it in the schema.

Check structure before values

First verify that the input parses as the expected outer structure, such as a JSON object. Then check for missing required keys, unexpected keys if strict mode is enabled, and type mismatches. Be careful with booleans in languages where a Boolean can be treated as a number; a field intended for a measurement should not accept true accidentally.

Next apply field-specific constraints. A numeric reading might need to be finite, while a timestamp might need to match a documented format. Do not impose physical ranges unless the protocol defines them or the project explicitly configures them. Validation should distinguish protocol requirements from optional quality checks.

Make each error actionable

Report errors with a field path and a short explanation: value: expected number, received string. For a missing field, say that it is required; for an invalid nested property, include the path such as location.latitude. Collect independent errors in one pass where safe, so the user can fix several issues together.

A message with a valid sensor ID but a string value of 18.2 should produce a type error if the contract requires a numeric JSON value. Automatically converting it may hide a producer inconsistency. If coercion is allowed, make it an explicit mode and report that conversion occurred.

Separate validation from repair

The validator should not mutate the message to make it pass. Return a clear valid or invalid result, the diagnostics, and a useful process exit code for automation. Keep the original input available for debugging, while avoiding unnecessary exposure of sensitive payloads in logs.

Test examples for a valid message, a missing key, a wrong type, and an extra field under the chosen policy. The finished tool is most useful when the schema is visible, errors point to exact fields, and every accepted transformation is documented.

Suggest a correction · All posts