Validate JSON Schema with Ajv

A practical review of validating JSON against a schema with Ajv: what it checks, when it changes your data, how to read its errors, and when plain parsing is enough.

Ajv is a JavaScript library that checks whether a JSON value matches a JSON Schema. It is widely used in Node.js services, build tooling and browser code to reject malformed configuration files, API payloads and form data before they reach application logic. This review covers what Ajv validation does and does not change, the settings that can alter your data, how usable its output is, and when a simpler check is the better choice.

Is Ajv the right tool for your use?

Ajv is a good fit when you need to enforce structure, not just syntax. Examples include required fields, value types, numeric ranges, string patterns, allowed enum values and rules about extra properties. Its main benefit is that you write those rules once, as a schema, and get a reusable validation function instead of hand-written checks scattered through the code.

The main tradeoff is setup and strictness. You need to pick the right schema draft, add format support separately, and deal with strict-mode errors when a schema has unknown keywords or ambiguous constructs. Some options also modify the data you validate. That is useful when you intend it, and surprising when you do not.

A plain check is preferable in several cases. If you only need to know whether a string is valid JSON, a call to JSON.parse inside a try/catch is enough. If you only want readable indentation, a formatter is the right tool. If the data shape is tiny and unlikely to change, a few explicit conditionals may be easier to maintain than a schema.

Task | What it checks or changes | Typical tool
Syntax check | Whether the text parses as JSON at all | JSON.parse or a JSON linter
Formatting | Whitespace, indentation and key layout only; values are unchanged | A JSON formatter or pretty-printer
Schema validation | Whether parsed data matches declared structure and constraints | Ajv or another JSON Schema validator

What Ajv actually changes

By default, Ajv does not transform your JSON. It reads a schema, compiles it into a JavaScript validation function, and runs that function against already-parsed data. The function returns true or false. When validation fails, it sets an errors array on the function that describes what went wrong. The input object is left as it was.

Ajv validates JavaScript values, not raw text. Text must be parsed first, so syntax errors such as a trailing comma or an unquoted key are reported by the parser, not by Ajv. Whitespace, key order and number formatting in the original text are not part of what the schema sees.

Several documented options do change the data in place, so enable them deliberately:

  • useDefaults: inserts default values declared in the schema into the validated object when properties are missing.
  • removeAdditional: deletes properties that the schema does not allow, depending on the mode chosen.
  • coerceTypes: converts values to the schema's declared type where possible, for example a numeric string to a number.
  • If the original payload must be preserved, for audit logging or for forwarding unchanged, validate a copy or leave these options off.

Choosing the schema draft

JSON Schema has several published drafts, and keyword behavior differs between them. Ajv's default export targets draft-07, which is also compatible with draft-06. Separate classes are provided for draft 2019-09 and draft 2020-12, and a companion package covers draft-04. Ajv also supports JSON Type Definition (JTD) through its own entry point, which is a different schema language and not interchangeable with JSON Schema. Match the class to the draft your schemas declare in their $schema keyword. Otherwise, keywords such as prefixItems or unevaluatedProperties may be rejected or handled differently than you expect.

A minimal example

The snippet below uses the default draft-07 class, enables allErrors so every failure is reported rather than only the first, and adds the separate formats package. Since Ajv version 7, the format keyword (for example "email") only checks values when a format package or custom formats are added.

const Ajv = require("ajv");
const addFormats = require("ajv-formats");

const ajv = new Ajv({ allErrors: true });
addFormats(ajv);

const schema = {
  type: "object",
  properties: {
    id: { type: "integer", minimum: 1 },
    email: { type: "string", format: "email" }
  },
  required: ["id", "email"],
  additionalProperties: false
};

const validate = ajv.compile(schema);
const data = { id: 0, email: "not-an-email", extra: true };

if (!validate(data)) {
  console.log(validate.errors);
}

Based on the schema, this input should fail three ways: id is below the minimum, email does not match the email format, and extra is not an allowed property. This expectation comes from the schema rules, not from a recorded test run. No output was captured for this article, so treat it as an illustration and run it in your own environment to confirm the exact error objects.

For performance, compile a schema once and reuse the returned function. Compiling on every request repeats code generation that only needs to happen once.

Is the output readable and usable?

Each entry in Ajv's errors array is a structured object. In current versions it includes an instancePath pointing to the failing location in the data, a schemaPath pointing to the rule that failed, the keyword involved, keyword-specific params and a short English message. This suits developers and logs well. It is not written for end users.

If people other than developers will see validation results, translate the errors into plain, field-specific sentences in your own interface. Companion packages exist for custom error messages and for localized messages, but they still require you to decide how errors appear to readers. No testing with screen readers or other assistive technology was available for this review. The accessibility of the final message depends on how your application presents it, not on Ajv itself.

The errors array is plain data, so it can be serialized to JSON, logged or returned from an API without special handling. The paths use JSON Pointer syntax, which is precise but can be hard to read when property names contain slashes or tildes, because those characters are escaped.

Strict mode and untrusted schemas

Recent Ajv versions run in strict mode by default. Strict mode reports unknown keywords and some schema patterns that are likely mistakes, rather than ignoring them. This catches typos such as a misspelled keyword that would otherwise silently disable a rule. It can also cause failures when you load third-party schemas that use custom keywords, which you can register or allow explicitly.

Ajv generates JavaScript code from schemas. Its documentation advises treating schemas as code and not compiling schemas from untrusted sources. Validating untrusted data against your own schemas is the intended use. Accepting arbitrary schemas from users is a separate risk to assess, including the cost of complex regular expressions in pattern keywords.

What this review could not verify

No benchmark figures, version-specific test results or environment-specific observations were available. Statements about behavior here reflect Ajv's documented design and general JSON Schema principles. Check option names and defaults against the documentation for the version you install, since some names and defaults have changed between major releases.