Skip to content

JSON Schema Validator — JavaScript source

Validate a JSON document against a draft-07 subset schema: types, required, bounds, patterns, enums, arrays and strict objects, every issue reported at its exact path. Pairs with the schema generator. Runs locally with a shareable link.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// json-schema-validator — draft-07 SUBSET JSON Schema validator. JavaScript
// port (canonical TS: src/lib/json-schema-validator.ts; Go twin:
// cli/json-schema-validator). Validates a JSON instance against a schema
// supporting: type (string or array, "integer" counts as "number"), enum,
// const, minimum/maximum/exclusiveMinimum/exclusiveMaximum, minLength/
// maxLength (TS .length = UTF-16 code units), pattern, minItems/maxItems,
// uniqueItems, items, required, properties, additionalProperties: false, and
// the boolean schemas true/false. Unsupported keywords ($ref/$defs, oneOf/
// anyOf/allOf/not, patternProperties, dependencies, format, propertyNames,
// contains) are ignored, exactly like the TS lib and the Go twin; the
// companion generator (json-to-schema) never emits any of them. Numbers print
// into messages with JS Number-to-string rules (70000, 1.5e-7, 1e+21).
// Never throws — errors travel in the result object.
'use strict';

function kindOf(v) {
  if (Array.isArray(v)) return 'array';
  if (v === null) return 'null';
  if (typeof v === 'boolean') return 'boolean';
  if (typeof v === 'number') return Number.isInteger(v) ? 'integer' : 'number';
  if (typeof v === 'object') return 'object';
  return 'string';
}

// Kind-sensitive structural equality (kindOf decides; objects compare by key
// sets, arrays element-wise, NaN never equals itself).
function deepEqual(a, b) {
  if (a === b) return true;
  if (kindOf(a) !== kindOf(b)) return false;
  if (Array.isArray(a) && Array.isArray(b)) {
    return a.length === b.length && a.every((x, i) => deepEqual(x, b[i]));
  }
  if (a !== null && b !== null && typeof a === 'object' && typeof b === 'object') {
    const ka = Object.keys(a);
    return ka.length === Object.keys(b).length && ka.every((k) => k in b && deepEqual(a[k], b[k]));
  }
  return false;
}

// Validate one value against one schema node, appending issues with paths.
// Issue order is part of the contract: type, enum, const, numeric bounds,
// string rules, array rules (uniqueItems before items), object rules
// (required, properties, additionalProperties).
function validate(v, schema, path, out) {
  if (schema === true) return;
  if (schema === false) {
    out.push({ path, message: 'no value is allowed here (schema is false)' });
    return;
  }
  if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {
    out.push({ path, message: 'invalid schema node: expected an object or boolean' });
    return;
  }

  if (schema.type !== undefined) {
    const allowed = Array.isArray(schema.type) ? schema.type.map(String) : [String(schema.type)];
    const actual = kindOf(v);
    const ok = allowed.some((t) => t === actual || (t === 'number' && actual === 'integer'));
    if (!ok) out.push({ path, message: 'expected type ' + allowed.join('|') + ', got ' + actual });
  }

  if (schema.enum !== undefined) {
    const list = Array.isArray(schema.enum) ? schema.enum : [];
    if (!list.some((e) => deepEqual(v, e))) {
      out.push({ path, message: 'value not in enum (' + list.length + ' allowed)' });
    }
  }

  if (schema.const !== undefined && !deepEqual(v, schema.const)) {
    out.push({ path, message: 'value does not match const' });
  }

  if (typeof v === 'number') {
    if (typeof schema.minimum === 'number' && v < schema.minimum) {
      out.push({ path, message: v + ' is less than minimum ' + schema.minimum });
    }
    if (typeof schema.maximum === 'number' && v > schema.maximum) {
      out.push({ path, message: v + ' is greater than maximum ' + schema.maximum });
    }
    if (typeof schema.exclusiveMinimum === 'number' && v <= schema.exclusiveMinimum) {
      out.push({ path, message: v + ' is not greater than exclusiveMinimum ' + schema.exclusiveMinimum });
    }
    if (typeof schema.exclusiveMaximum === 'number' && v >= schema.exclusiveMaximum) {
      out.push({ path, message: v + ' is not less than exclusiveMaximum ' + schema.exclusiveMaximum });
    }
  }

  if (typeof v === 'string') {
    if (typeof schema.minLength === 'number' && v.length < schema.minLength) {
      out.push({ path, message: 'string length ' + v.length + ' is less than minLength ' + schema.minLength });
    }
    if (typeof schema.maxLength === 'number' && v.length > schema.maxLength) {
      out.push({ path, message: 'string length ' + v.length + ' is greater than maxLength ' + schema.maxLength });
    }
    if (typeof schema.pattern === 'string') {
      try {
        if (!new RegExp(schema.pattern).test(v)) {
          out.push({ path, message: 'string does not match pattern ' + schema.pattern });
        }
      } catch {
        out.push({ path, message: 'invalid pattern in schema: ' + schema.pattern });
      }
    }
  }

  if (Array.isArray(v)) {
    if (typeof schema.minItems === 'number' && v.length < schema.minItems) {
      out.push({ path, message: 'array length ' + v.length + ' is less than minItems ' + schema.minItems });
    }
    if (typeof schema.maxItems === 'number' && v.length > schema.maxItems) {
      out.push({ path, message: 'array length ' + v.length + ' is greater than maxItems ' + schema.maxItems });
    }
    if (schema.uniqueItems === true) {
      for (let i = 0; i < v.length; i++) {
        for (let j = i + 1; j < v.length; j++) {
          if (deepEqual(v[i], v[j])) {
            out.push({ path: path + '[' + j + ']', message: 'duplicate item (same as index ' + i + ')' });
          }
        }
      }
    }
    if (schema.items !== undefined) {
      v.forEach((item, i) => validate(item, schema.items, path + '[' + i + ']', out));
    }
  }

  if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
    if (Array.isArray(schema.required)) {
      for (const key of schema.required.map(String)) {
        if (!(key in v)) out.push({ path, message: 'missing required property "' + key + '"' });
      }
    }
    const props = schema.properties ?? {};
    for (const key of Object.keys(props)) {
      if (key in v) validate(v[key], props[key], path + '.' + key, out);
    }
    if (schema.additionalProperties === false) {
      const known = new Set(Object.keys(props));
      for (const key of Object.keys(v)) {
        if (!known.has(key)) out.push({ path: path + '.' + key, message: 'additional property not allowed' });
      }
    }
  }
}

// Validate a JSON document (instanceRaw) against a schema (schemaRaw).
// Returns { valid, issues: [{path, message}], error } — error is null when
// the verdict is real, a message when the inputs could not be checked.
function validateJsonSchema(schemaRaw, instanceRaw) {
  if (!schemaRaw.trim() || !instanceRaw.trim()) {
    return { valid: false, issues: [], error: 'Both a schema and an instance are required' };
  }
  let schema;
  let instance;
  try {
    schema = JSON.parse(schemaRaw);
  } catch (e) {
    return { valid: false, issues: [], error: 'Schema: ' + (e instanceof Error ? e.message : 'Invalid JSON') };
  }
  try {
    instance = JSON.parse(instanceRaw);
  } catch (e) {
    return { valid: false, issues: [], error: 'Instance: ' + (e instanceof Error ? e.message : 'Invalid JSON') };
  }
  const issues = [];
  validate(instance, schema, '$', issues);
  return issues.length === 0
    ? { valid: true, issues: [], error: null }
    : { valid: false, issues, error: null };
}

// Example:
// validateJsonSchema(
//   '{"type":"object","required":["port"],"properties":{"port":{"type":"integer","minimum":1024}}}',
//   '{"port":80}')
// → { valid: false, issues: [{ path: '$.port', message: '80 is less than minimum 1024' }], error: null }

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →