Ajv is a powerful JSON validator for JavaScript. It makes sure your data follows the structure you want. It works quickly by transforming schemas into optimized JavaScript functions, making it one of the fastest validators available.
The library checks everything from basic types to complex formats. It can handle conditional validation and custom rules too. Because it's so fast and thorough, Ajv has become the go-to validator for Node.js projects.
In this guide, you'll learn how to set up Ajv, create schemas, validate data, and add your own validation rules.
Prequisites
Before starting, make sure you have Node.js version 22.0 or higher installed. Ajv uses modern JavaScript features, so you need an up-to-date version.
Check your Node.js version by running:
Setting up your project
Let's set up a project folder and install the necessary components. Having a dedicated project helps keep your validation code organized and maintainable.
Create a new directory and move into it:
Start a new Node.js project:
Set up your project to use ES modules:
Install Ajv and the formats package:
Test that Ajv installed correctly by creating a test file:
Add this code to the file:
Run the file to check:
If you see something like:
Then Ajv is installed and ready to use.
Getting started with Ajv
Now that we've seen a basic example, let's take a closer look at how the validation process unfolds step by step.
The following sequence diagram shows the interaction between the developer, Ajv, and the validation function, highlighting the three key phases: initial setup, schema compilation, and data validation:
Understanding this sequence will help you work more effectively with Ajv in your applications.
Ajv checks if your JSON data matches the structure you defined. It makes special JavaScript functions from your schemas to validate data quickly.
Let's create your first validation. Make a file called main.js and add this code:
This code uses the Ajv library to validate data based on a defined schema. It creates a schema that checks if the data has a name (string) and age (integer) and ensures that no extra properties are present.
The code then checks if the data ({ name: "Alice", age: 30 }) meets the requirements of the schema. If the data is valid, it prints "Data is valid!" Otherwise, it shows the validation errors.
Run the script:
You'll see:
What happens when the data doesn't match? Try this:
Rerun it, and you'll see:
Unlike some other tools, Ajv doesn't automatically convert types. Even if you try with a number as a string:
You'll still get an error because "30" is a string, not an integer.
If you want Ajv to convert types for you, you can set that up:
Upon running the file, you will see:
Now, let's examine how to add rules to refine your validation.
Adding rules to your schemas
Basic type checking is often not enough. You typically need additional rules to maintain high-quality data. Ajv gives you many validators to set these rules.
Update your schema with more specific rules:
Now, each field has specific rules: the name must be between 2 and 50 characters, the age must be between 1 and 120, and the email must be in a valid email format.
We've also enabled the allErrors option, which finds all errors simultaneously instead of stopping at the first one.
When you run the file, you will see no issues:
Try data that breaks these rules:
When you run the file, you'll get errors for all three fields:
Checking early helps catch problems before they cause issues in your application.
Sometimes you want to make fields optional. By default, all properties in a JSON Schema are optional unless you list them in the required array.
To make some fields optional:
Now data without an email is still valid:
You can also set default values for missing fields. To make Ajv use these defaults, enable the useDefaults option:
Now when a field with a default value is missing, Ajv adds it automatically:
You'll see:
The isActive property was set to true automatically.
Creating custom validation rules
Sometimes the built-in rules aren't enough. You might need special validation for things like:
- Username formats
- Password requirements
- Date ranges
- Relationships between fields
Ajv lets you create custom keywords for these special cases.
The diagram below outlines the process of creating and registering a custom keyword with Ajv, with a password complexity validator as a practical example. This flowchart breaks down the steps we'll implement in the code that follows:
Here's how to add a password validation rule:
The highlighted code adds a custom password validation rule that checks if the password contains at least one uppercase letter, one lowercase letter, and one number.
This is done by defining a custom validation keyword called passwordComplexity. In the schema, the password field uses this keyword along with a requirement that the password must be at least 8 characters long.
The code then validates the user data, { username: "alice123", password: "Secure123" }, against the schema. If the data meets all the requirements, it prints "User data is valid!". Otherwise, it outputs any validation errors.
Now, run the following command:
Now try an invalid password:
You'll get:
This output indicates that the password failed the custom validation rule defined in the schema, passwordComplexity.
The validation checks whether the password contains at least one uppercase letter, one lowercase letter, and one number. Since the password "weakpass" doesn't meet these criteria, it fails the validation, and the error message is displayed.
Custom rules enable you to create the exact validation you need for your specific use case.
Final thoughts
In this guide, we show you how to set up Ajv, create rules, and verify data, including how to make your own rules, such as checking password complexity.
To learn more about Ajv and how to use it, check out the official Ajv documentation.