Schema Validation In JavaScript

Have you ever found yourself in a situation where you're unsure if the data your application receives is correct? Perhaps you've built a captivating form, only to discover that the responses are cringe-worthy and inconsistent, leading to errors in your application later on. It's frustrating, isn't it? This is a common problem for many developers. Luckily, I'm here to offer you a practical solution: schema validation with the AJV (Another JSON Schema Validator) library. In this article, we'll dive into what schema validation is, why it's essential, and how you can leverage the AJV library to ensure that the data flowing into your application is valid and trustworthy. Don't worry; I'll guide you through every step of the process. By the end of this article, you will be ready to implement schema validation like a pro! Why Use AJV for Schema Validation? AJV is a popular lightweight JSON schema validator that's not only fast but also offers a rich set of features. It's widely used by developers who need to ensure that their data structures adhere to a specific format. In short, using AJV can enhance data integrity, reduce errors, and simplify debugging in your applications. And believe me, I've faced countless debugging sessions where timely schema validation could have saved me hours. You can get started with AJV by installing it via npm: npm install ajv Let's look into some common questions people have when it comes to schema validation using AJV. 1. What is schema validation? Schema validation involves defining a structure (or schema) that your data should adhere to and checking incoming data against this standard. For example, if your API endpoint expects an object with specific properties, a schema definition will ensure that the data received meets these requirements. 2. How do I use AJV in my project? Using AJV is straightforward. Here's a step-by-step example for you. First, define a JSON schema. Let's say you need to validate user profiles with the following structure: name (string, required) age (integer, required) email (string, must match email format) Here's how you could define that schema: const userSchema = { type: "object", properties: { name: { type: "string" }, age: { type: "integer", minimum: 0 }, email: { type: "string", format: "email" }, }, required: ["name", "age", "email"], }; Now, to validate an incoming user object, follow these steps: const Ajv = require("ajv"); const ajv = new Ajv(); const validate = ajv.compile(userSchema); // Example user data const userData = { name: "John Doe", age: 30, email: "john.doe@example.com", }; const valid = validate(userData); if (!valid) { console.log(validate.errors); } else { console.log("User data is valid!"); } 3. What happens if the data doesn't match the schema? If the data doesn't match the defined schema, AJV provides detailed error messages. This is where the magic happens! You'll see information such as which property was incorrect and what values were expected. Here's an example object that fails validation: const invalidUserData = { name: "Jane Doe", age: -10, // Invalid age }; const validInvalid = validate(invalidUserData); if (!validInvalid) { console.error(validate.errors); // This will show the specific error messages } 4. Can I use AJV for complex validations? Absolutely! AJV supports many advanced features, including arrays, nested objects, and custom validation keywords. You can even define your own keywords for specific needs. It's incredibly powerful! For example, to define an array of items, you could do something like this: const shoppingListSchema = { type: "object", properties: { items: { type: "array", items: { type: "string" }, minItems: 1, }, }, }; 5. Example - Function to Generate/Validate JSON Schema Here is a function that takes 2 arguments { response: APIResponse, fileName: string } and generate the equivalent JSON schema. json-schema-generator - https://www.npmjs.com/package/json-schema-generator import { APIResponse} from '@playwright/test' import { promises as fs } from 'fs' import generateSchema from 'json-schema-generator' import path from 'path' async generateJsonSchema(options: { response: APIResponse, fileName: string }): Promise { const responseBody: APIResponse = await options.response.json() const jsonSchema = generateSchema(responseBody) const schemaFolderPath = path.resolve(__dirname, '../../test/schema') const filePath = path.join(schemaFolderPath, `${options.fileName}.json`) await fs.mkdir(schemaFolderPath, { recursive: true }) await fs.writeFile(filePath, JSON.stringify(jsonSchema, null, 2)) return this } Function to validate JSON Schema - import { APIResponse} from '@playwright/test' import Ajv from "ajv" import AjvDraft04 from 'ajv-draft-04' impo

Jan 17, 2025 - 17:17
Schema Validation In JavaScript

Image description

Have you ever found yourself in a situation where you're unsure if the data your application receives is correct? Perhaps you've built a captivating form, only to discover that the responses are cringe-worthy and inconsistent, leading to errors in your application later on.
It's frustrating, isn't it?

This is a common problem for many developers. Luckily, I'm here to offer you a practical solution: schema validation with the AJV (Another JSON Schema Validator) library.

In this article, we'll dive into what schema validation is, why it's essential, and how you can leverage the AJV library to ensure that the data flowing into your application is valid and trustworthy.
Don't worry; I'll guide you through every step of the process. By the end of this article, you will be ready to implement schema validation like a pro!

Why Use AJV for Schema Validation?

AJV is a popular lightweight JSON schema validator that's not only fast but also offers a rich set of features. It's widely used by developers who need to ensure that their data structures adhere to a specific format.
In short, using AJV can enhance data integrity, reduce errors, and simplify debugging in your applications. And believe me, I've faced countless debugging sessions where timely schema validation could have saved me hours.
You can get started with AJV by installing it via npm:

npm install ajv

Let's look into some common questions people have when it comes to schema validation using AJV.

1. What is schema validation?

Schema validation involves defining a structure (or schema) that your data should adhere to and checking incoming data against this standard. For example, if your API endpoint expects an object with specific properties, a schema definition will ensure that the data received meets these requirements.

2. How do I use AJV in my project?

Using AJV is straightforward. Here's a step-by-step example for you. First, define a JSON schema. Let's say you need to validate user profiles with the following structure:

name (string, required)
age (integer, required)
email (string, must match email format)

Here's how you could define that schema:
const userSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "integer", minimum: 0 },
    email: { type: "string", format: "email" },
  },
  required: ["name", "age", "email"],
};

Now, to validate an incoming user object, follow these steps:

const Ajv = require("ajv");
const ajv = new Ajv();
const validate = ajv.compile(userSchema);

// Example user data
const userData = {
  name: "John Doe",
  age: 30,
  email: "john.doe@example.com",
};

const valid = validate(userData);

if (!valid) {
  console.log(validate.errors);
} else {
  console.log("User data is valid!");
}

3. What happens if the data doesn't match the schema?

If the data doesn't match the defined schema, AJV provides detailed error messages.
This is where the magic happens! You'll see information such as which property was incorrect and what values were expected. Here's an example object that fails validation:

const invalidUserData = {
  name: "Jane Doe",
  age: -10, // Invalid age
};

const validInvalid = validate(invalidUserData);

if (!validInvalid) {
  console.error(validate.errors); // This will show the specific error messages
}

4. Can I use AJV for complex validations?

Absolutely! AJV supports many advanced features, including arrays, nested objects, and custom validation keywords. You can even define your own keywords for specific needs. It's incredibly powerful! For example, to define an array of items, you could do something like this:

const shoppingListSchema = {
  type: "object",
  properties: {
    items: {
      type: "array",
      items: { type: "string" },
      minItems: 1,
    },
  },
};

5. Example - Function to Generate/Validate JSON Schema

Here is a function that takes 2 arguments { response: APIResponse, fileName: string } and generate the equivalent JSON schema.
json-schema-generator - https://www.npmjs.com/package/json-schema-generator

import { APIResponse} from '@playwright/test'
import { promises as fs } from 'fs'
import generateSchema from 'json-schema-generator'
import path from 'path'

async generateJsonSchema(options: { response: APIResponse, fileName: string }): Promise {
        const responseBody: APIResponse = await options.response.json()
        const jsonSchema = generateSchema(responseBody)

        const schemaFolderPath = path.resolve(__dirname, '../../test/schema')
        const filePath = path.join(schemaFolderPath, `${options.fileName}.json`)

        await fs.mkdir(schemaFolderPath, { recursive: true })
        await fs.writeFile(filePath, JSON.stringify(jsonSchema, null, 2))

        return this
    }

Function to validate JSON Schema -

import { APIResponse} from '@playwright/test'
import Ajv from "ajv"
import AjvDraft04 from 'ajv-draft-04'
import addFormats from 'ajv-formats'

async validateJsonSchema(response: APIResponse, schema: Record): Promise {
        const ajv: Ajv = new AjvDraft04()
        addFormats(ajv)
        const validate = ajv.compile(schema)
        const valid = validate(await response.json())
        if (!valid) {
            throw new Error(`JSON Schema validation failed: ${JSON.stringify(validate.errors)}`)
        }

        return this
    }

6. Where can I learn more about AJV?

The official AJV documentation is an excellent resource that covers everything from installation to advanced validation scenarios. Additionally, community forums and platforms like Stack Overflow often have discussions that can be beneficial.
Empower Your Applications!

In the realm of development, ensuring that your data is valid is like putting on your seatbelt before driving - it's a safety measure that can save you from serious accidents down the road. Implementing schema validation with AJV not only brings structure to your code but also saves you time by catching errors early in the development process.

I hope you found this guide helpful! If you try out AJV, don't be discouraged if you encounter some hiccups along the way. Learning is a journey, and the more you practice, the better you'll get. So go ahead, implement schema validation in your projects, and watch your applications thrive! And remember, every mistake is just a stepping stone to mastery.

Interested in enhancing your technical stack further?
Check out the AJV GitHub repository or look into other great validation libraries to see what fits your needs.
Happy coding!