SyntaxStudy
Sign Up
JavaScript JSON Schema Validation
JavaScript Advanced 6 min read

JSON Schema Validation

JSON Schema

JSON Schema is a standard for describing and validating JSON data structures. Use libraries like Ajv to validate incoming data against a schema.

Example
import Ajv from "ajv";
const ajv = new Ajv();

const schema = {
  type: "object",
  properties: {
    name:  { type: "string", minLength: 1 },
    age:   { type: "integer", minimum: 0, maximum: 120 },
    email: { type: "string", format: "email" },
  },
  required: ["name", "email"],
  additionalProperties: false,
};

const validate = ajv.compile(schema);
const valid = validate({ name: "Alice", email: "alice@example.com", age: 30 });
// true

validate({ name: "" }); // false — name too short, email missing
Pro Tip

Validate all external JSON data (API responses, user input) against a schema before using it in your application.