Stop Writing Validation If-Else Blocks: Use JSON Schema
Stop cluttering your business logic with manual if-else checks. Learn how to use JSON Schema for declarative validation, strict contract enforcement, and polymorphic data handling.
28 Feb 2026, 14:08 UTC

Many microservices rely on a mountain of defensive conditional logic. When a request arrives, the code manually checks if a field exists, if a string meets a length requirement, or if a number falls within a specific range. This imperative approach is brittle, difficult to document, and litters core business logic with boilerplate validation code.
The solution is to shift to declarative validation using JSON Schema. By defining your data contract in a separate schema file, you decouple what the data should look like from how your application processes it. This allows you to reject malformed data at the edge—such as an API Gateway or middleware—before it ever reaches your downstream business logic.
Enforcing Strict Contracts with additionalProperties
A common risk in evolving APIs is "data drift," where a client sends unexpected fields. While an application might ignore these fields, they can inadvertently be persisted in a database or cause unexpected behavior in loosely typed languages. In JSON Schema, the additionalProperties: false constraint is the primary tool for strict contract enforcement. It ensures the validator fails if any field not explicitly defined in the schema is present in the payload.
Handling Polymorphism with oneOf
Real-world data is rarely uniform. For example, a "payment" object might accept either credit card details or a crypto-wallet address. Instead of writing nested logic to determine which type of payment is being processed, you can use the oneOf keyword. This requires that the data matches exactly one of the provided sub-schemas, allowing your API to handle multiple input formats while maintaining strict type-checking for each specific variant.
Worked Example: Validating a User Profile
Consider a user registration event where we need to ensure the email is valid, the age is within an adult range, and no extra fields are allowed. This schema follows the Draft 2020-12 specification.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"username": { "type": "string", "minLength": 3 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 18 },
"role": {
"oneOf": [
{ "const": "admin" },
{ "const": "user" }
]
}
},
"required": ["username", "email"],
"additionalProperties": false
}
To implement this in a Node.js environment, you can use the Ajv library. Run this with npm install ajv ajv-formats to ensure the "email" format is supported:
// Required permissions: Node.js runtime environment
const Ajv = require('ajv');
const addFormats = require('ajv-formats');
const ajv = new Ajv();
addFormats(ajv);
const schema = { /* Insert schema from above */ };
const validate = ajv.compile(schema);
const data = { "username": "jdoe", "email": "[contact removed]", "age": 25, "role": "user" };
const valid = validate(data);
if (!valid) {
console.log("Validation errors:", validate.errors);
} else {
console.log("Data is valid");
}
Risk: If you omit the ajv-formats plugin, the "format": "email" constraint may be ignored by default, allowing invalid email strings to pass.
Performance and Versioning Trade-offs
Declarative validation is not without cost. Deeply nested schemas or heavy use of recursive references ($ref) can increase CPU consumption. In high-throughput environments validating thousands of payloads per second, these overheads can become significant. It is practical to measure validation latency specifically when adding complex constraints like additionalProperties.
Additionally, JSON Schema versions (e.g., Draft 7 vs. Draft 2020-12) have breaking changes in keyword behavior. Always verify that your chosen library supports the specific draft version defined in your $schema declaration to avoid silent validation failures.
Verification and Implementation
To verify your implementation, test your schema against three distinct payloads: one perfectly valid, one missing a required field, and one containing an undefined field. If additionalProperties: false is working, the third payload must be rejected.
Start by identifying your most critical data contracts. Replace manual if-else blocks with a strict JSON Schema and implement the check as a middleware layer to keep your business logic clean.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.