Lightweight JSON validator with flexible validation rules.

Example

const validator = new JSONValidator();

const template = {
"name": "John Doe", // Required field
"email?": "user@example.com", // Optional field
"settings*": {}, // Required, any content
"tags:[1+]": ["tag1"], // Array with 1+ items
"age:number": 25 // Must be number
};

const data = {
name: "Jane Smith",
tags: ["work", "urgent"],
age: 30
};

const result = validator.validate(data, template);
if (result.Success) {
console.log('Validation passed!');
}

Constructors

Methods

  • Cleans validation syntax from JSON object keys.

    This method recursively processes a JSON object and removes validation syntax markers (?, *, :rules) from all object keys. This is useful when AI models mistakenly include our validation syntax in their responses.

    Type Parameters

    • T

      The expected type of the cleaned data

    Parameters

    • data: unknown

      The JSON data to clean

    Returns T

    A new object with cleaned keys, typed as T

    Example

    interface MyData {
    name: string;
    items: string[];
    config: { enabled: boolean };
    }

    const dirtyJson = {
    "name?": "John",
    "items:[1+]": ["a", "b"],
    "config*": { "enabled?": true }
    };

    const cleanJson = validator.cleanValidationSyntax<MyData>(dirtyJson);
    // Result is typed as MyData
  • Private

    Parses a field key to extract the field name and validation rules.

    Parameters

    • key: string

    Returns ParsedFieldInfo

  • Private

    Parses validation rules from a string, handling special cases like array syntax.

    Parameters

    • rulesString: string

    Returns string[]

  • Validates an object against a template with validation rules.

    Parameters

    • data: unknown

      The data object to validate

    • template: unknown

      The template object with validation rules

    • path: string = ''

      The current path in the object hierarchy (used internally)

    Returns ValidationResult

    ValidationResult with Success flag and any validation errors

  • Validates an object against a JSON schema string. Convenience method that parses the schema and validates.

    Parameters

    • data: unknown

      The data to validate

    • schemaJson: string

      JSON string containing the validation schema

    Returns ValidationResult

    ValidationResult with Success flag and any validation errors