Skip to main content

Ajv (Another JSON Schema Validator)

Ajv (Another JSON Schema Validator) is a high-performance JSON schema validator widely used in Node.js applications. It ensures that data conforms to a predefined structure and set of rules, which is crucial for maintaining data integrity and application stability.
Key Features and Usage in Node.js:
  • JSON Schema Validation: Ajv validates data against JSON Schema specifications (drafts 04, 06, 07, 2019-09, and 2020-12) and JSON Type Definition (JTD). This allows you to define the expected structure, data types, and constraints for your JSON data.
  • Performance: Ajv is known for its speed. It compiles schemas into optimized JavaScript functions, which are highly efficient for validating data, especially in performance-critical Node.js environments.
  • Installation: You can install Ajv in your Node.js project using npm: 

Code

    npm install ajv
Basic Usage.
JavaScript

    const Ajv = require('ajv');
    const ajv = new Ajv(); // Options can be passed here, e.g., { allErrors: true }

    const schema = {
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'integer', minimum: 0 }
      },
      required: ['name', 'age'],
      additionalProperties: false
    };

    const validate = ajv.compile(schema);

    const data = { name: 'John Doe', age: 30 };
    const valid = validate(data);

    if (!valid) {
      console.log(validate.errors); // Array of validation errors
    } else {
      console.log('Data is valid');
    }
  • Error Handling:
    When validation fails, validate.errors will contain an array of ErrorObject detailing the validation issues, which can be used to provide informative feedback to users or for debugging.
  • Integration with Frameworks:
    Ajv can be integrated with Node.js web frameworks like Express or Koa to validate incoming request bodies, ensuring that API payloads adhere to defined schemas. This helps in preventing invalid data from reaching your application logic.
  • Custom Keywords and Formats:
    Ajv allows for extending its capabilities with custom keywords and formats, enabling highly specific validation logic tailored to your application's needs. The ajv-formats plugin provides support for common formats like date, time, and email


    https://ajv.js.org/guide/getting-started.html