Schema Validator

Schema Validator

The SchemaValidator is responsible for validating and parsing input and output data. It supports various types, allowing for flexible and comprehensive data validation. The available types are:

  • String
  • Number
  • Boolean
  • Object
  • Array
  • File

String

Custom String Validations

The SchemaValidator.string() method allows you to apply several custom validations on string values:

SchemaValidator.string().max(64); // Maximum length of 64 characters
SchemaValidator.string().min(6); // Minimum length of 6 characters
SchemaValidator.string().length(10); // Exact length of 10 characters
SchemaValidator.string().url(); // Validates if the string is a URL
SchemaValidator.string().uuid(); // Validates if the string is a UUID
SchemaValidator.string().regex(); // Validates the string using a regular expression
SchemaValidator.string().includes("th"); // Checks if the string includes the substring "th"
SchemaValidator.string().startsWith("The"); // Checks if the string starts with "The"
SchemaValidator.string().endsWith("s"); // Checks if the string ends with "s"

Number

Custom Number Validations

The SchemaValidator.number() method allows for a variety of number validations:

SchemaValidator.number().gt(10); // Greater than 10
SchemaValidator.number().gte(12); // Greater than or equal to 12
SchemaValidator.number().lt(8); // Less than 8
SchemaValidator.number().lte(10); // Less than or equal to 10
SchemaValidator.number().integer(); // Ensures the number is an integer (non-fractional)
SchemaValidator.number().positive(); // Positive numbers only
SchemaValidator.number().nonnegative(); // Non-negative numbers (including 0)
SchemaValidator.number().negative(); // Negative numbers only
SchemaValidator.number().nonpositive(); // Non-positive numbers (including 0)
SchemaValidator.number().multipleOf(5); // Ensures the number is a multiple of 5

Boolean

Validates boolean values, checking for either true or false.


Object

An object can consist of multiple fields, each with its own validation rules. For example:

SchemaValidator.object({
    username: SchemaValidator.string(),
    age: SchemaValidator.number(),
    // Other fields...
});

Array

Arrays can be validated with a specified type for their elements. For example, to validate an array of objects with a username field:

SchemaValidator.array(SchemaValidator.object({
    username: SchemaValidator.string(),
}));
// Expects an array like: [{ username: "User1" }, { username: "User2" }]

File

Validates Buffer data, typically read from a file, to ensure it meets specific requirements.


The SchemaValidator provides a flexible and powerful way to validate different types of data in your application, ensuring consistency and reliability in your inputs and outputs.