JSON schema validator for JavaScript with comprehensive validation capabilities and support for both synchronous and asynchronous validation modes
Core validation functionality for validating JSON data against JSON Schema specifications, with support for both synchronous and asynchronous validation modes.
Creates a new validator instance with optional configuration.
/**
* Create a new z-schema validator instance
* @param options - Configuration options for validation behavior
*/
constructor(options?: ZSchema.Options);Usage Examples:
const ZSchema = require("z-schema");
// Default validator
const validator = new ZSchema();
// Strict mode validator
const strictValidator = new ZSchema({
strictMode: true,
breakOnFirstError: true
});
// Custom configuration
const customValidator = new ZSchema({
asyncTimeout: 5000,
noEmptyStrings: true,
reportPathAsArray: true
});Validates JSON data against a schema with support for both sync and async modes.
/**
* Validate JSON data against a schema
* @param json - Data to validate
* @param schema - JSON schema to validate against
* @param options - Optional validation options
* @param callback - Optional callback for async validation
* @returns boolean (sync mode) or void (async mode)
*/
validate(
json: any,
schema: any,
options?: ValidateOptions,
callback?: (err: any, valid: boolean) => void
): boolean | void;
interface ValidateOptions {
schemaPath?: string;
includeErrors?: string[];
}Usage Examples:
const validator = new ZSchema();
// Synchronous validation
const schema = {
type: "object",
properties: {
name: { type: "string", minLength: 1 },
age: { type: "number", minimum: 0 }
},
required: ["name", "age"]
};
const data = { name: "Alice", age: 25 };
const valid = validator.validate(data, schema);
if (!valid) {
console.log(validator.getLastErrors());
}
// Asynchronous validation (required for schemas with async format validators)
validator.validate(data, schema, function(err, valid) {
if (err) {
console.error("Validation error:", err);
} else if (!valid) {
console.log("Validation failed:", validator.getLastErrors());
} else {
console.log("Validation passed");
}
});
// Validation with schema path (validate against subschema)
const complexSchema = {
definitions: {
user: {
type: "object",
properties: {
name: { type: "string" }
}
}
}
};
const valid = validator.validate(
{ name: "Bob" },
complexSchema,
{ schemaPath: "definitions.user" }
);
// Validation with specific error types only
const valid = validator.validate(data, schema, {
includeErrors: ["INVALID_TYPE", "MINIMUM"]
});Validates that a schema itself is a valid JSON Schema.
/**
* Validate that a schema is a valid JSON Schema
* @param schema - Schema to validate (can be single schema or array)
* @returns boolean indicating if schema is valid
*/
validateSchema(schema: any): boolean;Usage Examples:
const validator = new ZSchema();
// Single schema validation
const schema = {
type: "string",
minLength: 5
};
const isValidSchema = validator.validateSchema(schema);
if (!isValidSchema) {
console.log("Schema validation failed:", validator.getLastErrors());
}
// Multiple schema validation with references
const schemas = [
{
id: "personDetails",
type: "object",
properties: {
firstName: { type: "string" },
lastName: { type: "string" }
},
required: ["firstName", "lastName"]
},
{
id: "addressDetails",
type: "object",
properties: {
street: { type: "string" },
city: { type: "string" }
},
required: ["street", "city"]
},
{
id: "personWithAddress",
allOf: [
{ $ref: "personDetails" },
{ $ref: "addressDetails" }
]
}
];
const allSchemasValid = validator.validateSchema(schemas);
if (allSchemasValid) {
// Now validate data against compiled schemas
const data = {
firstName: "John",
lastName: "Doe",
street: "123 Main St",
city: "Anytown"
};
const valid = validator.validate(data, schemas[2]);
}Compiles a schema for validation without validating it against the meta-schema.
/**
* Compile a schema for validation without meta-schema validation
* @param schema - Schema to compile
* @returns boolean indicating compilation success
*/
compileSchema(schema: any): boolean;Usage Examples:
const validator = new ZSchema();
const schema = {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" }
}
};
// Compile schema (faster than validateSchema)
const compiled = validator.compileSchema(schema);
if (compiled) {
// Schema is ready for validation
const valid = validator.validate({ id: 1, name: "test" }, schema);
}interface TimeoutOptions {
/** Timeout in milliseconds for async operations (default: 2000) */
asyncTimeout?: number;
}interface ValidationBehaviorOptions {
/** Stop validation after first error (default: false) */
breakOnFirstError?: boolean;
/** Treat empty strings as invalid for string type (default: false) */
noEmptyStrings?: boolean;
/** Treat empty arrays as invalid for array type (default: false) */
noEmptyArrays?: boolean;
/** Require type to be specified in schemas (default: false) */
noTypeless?: boolean;
/** Case insensitive enum value matching (default: false) */
enumCaseInsensitiveComparison?: boolean;
}interface SchemaStrictnessOptions {
/** Require additionalProperties/additionalItems to be defined (default: false) */
forceAdditional?: boolean;
/** Assume additionalProperties/Items are false (default: false) */
assumeAdditional?: boolean | string[];
/** Require items to be defined for array schemas (default: false) */
forceItems?: boolean;
/** Require minItems to be defined for array schemas (default: false) */
forceMinItems?: boolean;
/** Require maxItems to be defined for array schemas (default: false) */
forceMaxItems?: boolean;
/** Require minLength to be defined for string schemas (default: false) */
forceMinLength?: boolean;
/** Require maxLength to be defined for string schemas (default: false) */
forceMaxLength?: boolean;
/** Require properties/patternProperties for object schemas (default: false) */
forceProperties?: boolean;
/** Enable multiple strict options at once (default: false) */
strictMode?: boolean;
}interface AdvancedOptions {
/** Don't fail on unresolvable remote references (default: false) */
ignoreUnresolvableReferences?: boolean;
/** Reject schemas with unrecognized keywords (default: false) */
noExtraKeywords?: boolean;
/** Require fully RFC3986 compliant URIs (default: false) */
strictUris?: boolean;
/** Don't report unknown formats as errors (default: false) */
ignoreUnknownFormats?: boolean;
/** Report error paths as arrays instead of strings (default: false) */
reportPathAsArray?: boolean;
/** Check schema best practices (default: false) */
pedanticCheck?: boolean;
/** Custom validation function called on every subschema (default: null) */
customValidator?: (report: any, schema: any, json: any) => void;
}Install with Tessl CLI
npx tessl i tessl/npm-z-schema