JSON Schema Validator — C# 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 C# implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-schema-validator — draft-07 SUBSET JSON Schema validator. C# 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 counts UTF-16 code units: astral chars are 2),
// 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. System.Text.Json enumerates JsonElement properties in
// document order (like JS Object.keys), so issue ordering matches. Patterns
// run through Regex with RegexOptions.ECMAScript. Numbers print into
// messages with JS Number-to-string rules via a jsNum port (70000, 1.5e-7,
// 1e+21). Never throws — errors travel in the result object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace JsonSchemaValidator;
public struct ValidationIssue
{
public string Path;
public string Message;
}
public class JsonSchemaValidateResult
{
public bool Valid;
public List<ValidationIssue> Issues = new();
public string Error; // null when the verdict is real (TS: error: null)
}
public static class Validator
{
static bool IsNum(JsonElement e) => e.ValueKind == JsonValueKind.Number;
static string KindOf(JsonElement v)
{
switch (v.ValueKind)
{
case JsonValueKind.Array: return "array";
case JsonValueKind.Null: return "null";
case JsonValueKind.Bool: return "boolean";
case JsonValueKind.Number:
return v.GetDouble() == Math.Truncate(v.GetDouble()) ? "integer" : "number";
case JsonValueKind.Object: return "object";
default: return "string";
}
}
// Kind-sensitive structural equality; objects compare by key sets.
static bool DeepEqual(JsonElement a, JsonElement b)
{
if (a.ValueKind != b.ValueKind) return false;
switch (a.ValueKind)
{
case JsonValueKind.Number:
return a.GetDouble() == b.GetDouble();
case JsonValueKind.String:
return a.GetString() == b.GetString();
case JsonValueKind.Array:
{
var aa = a.EnumerateArray().ToArray();
var ba = b.EnumerateArray().ToArray();
if (aa.Length != ba.Length) return false;
for (int i = 0; i < aa.Length; i++)
if (!DeepEqual(aa[i], ba[i])) return false;
return true;
}
case JsonValueKind.Object:
{
if (a.EnumerateObject().Count() != b.EnumerateObject().Count()) return false;
foreach (var p in a.EnumerateObject())
{
if (!b.TryGetProperty(p.Name, out var bv) || !DeepEqual(p.Value, bv)) return false;
}
return true;
}
default:
return true; // Null, True, False share the ValueKind test above
}
}
// JS Number-to-string: plain integers below 1e21, exponential only past
// the JS thresholds (decimal exponent < -6 or >= 21), minimal exponent
// digits ("1.5e-7", "1e+21").
static string JsNum(double v)
{
if (double.IsNaN(v)) return "NaN";
if (double.IsInfinity(v)) return v > 0 ? "Infinity" : "-Infinity";
if (v == 0) return "0";
bool neg = v < 0;
double a = Math.Abs(v);
if (a == Math.Truncate(a) && a < 1e21) return (neg ? "-" : "") + a.ToString("F0");
string text = a.ToString("R"); // shortest round-trip digits
string digits;
int exp;
int ei = text.IndexOfAny(new[] { 'e', 'E' });
if (ei >= 0)
{
exp = int.Parse(text.Substring(ei + 1));
digits = text.Substring(0, ei).Replace(".", "");
}
else
{
int dot = text.IndexOf('.');
string intPart = dot >= 0 ? text.Substring(0, dot) : text;
digits = intPart + (dot >= 0 ? text.Substring(dot + 1) : "");
exp = intPart.Length - 1;
while (digits.Length > 1 && digits[0] == '0') { digits = digits.Substring(1); exp--; }
}
string sign = neg ? "-" : "";
string head = digits[0] + (digits.Length > 1 ? "." + digits.Substring(1) : "");
if (exp < -6 || exp >= 21) return sign + head + "e" + (exp >= 0 ? "+" : "-") + Math.Abs(exp);
if (exp < 0) return sign + "0." + new string('0', -exp - 1) + digits;
if (digits.Length > exp + 1)
return sign + digits.Substring(0, exp + 1) + "." + digits.Substring(exp + 1);
return sign + digits + new string('0', exp + 1 - digits.Length);
}
// JS String(v) for schema type entries and required keys.
static string JsString(JsonElement v)
{
switch (v.ValueKind)
{
case JsonValueKind.Null: return "null";
case JsonValueKind.True: return "true";
case JsonValueKind.False: return "false";
case JsonValueKind.Number: return JsNum(v.GetDouble());
case JsonValueKind.String: return v.GetString();
case JsonValueKind.Array:
return string.Join(",", v.EnumerateArray().Select(JsString));
default: return "[object Object]";
}
}
// TS .length counts UTF-16 code units: astral chars (surrogate pairs) are 2.
static int Utf16Len(string s)
{
int n = 0;
foreach (char c in s)
{
if (char.IsLowSurrogate(c)) continue;
n += char.IsHighSurrogate(c) ? 2 : 1;
}
return n;
}
static void Issue(List<ValidationIssue> issues, string path, string message) =>
issues.Add(new ValidationIssue { Path = path, Message = message });
// 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).
static void Validate(JsonElement v, JsonElement schema, string path, List<ValidationIssue> issues)
{
if (schema.ValueKind == JsonValueKind.True) return;
if (schema.ValueKind == JsonValueKind.False)
{
Issue(issues, path, "no value is allowed here (schema is false)");
return;
}
if (schema.ValueKind != JsonValueKind.Object)
{
Issue(issues, path, "invalid schema node: expected an object or boolean");
return;
}
if (schema.TryGetProperty("type", out var tv))
{
var allowed = new List<string>();
if (tv.ValueKind == JsonValueKind.Array)
foreach (var x in tv.EnumerateArray()) allowed.Add(JsString(x));
else
allowed.Add(JsString(tv));
string actual = KindOf(v);
bool ok = allowed.Any(t => t == actual || (t == "number" && actual == "integer"));
if (!ok) Issue(issues, path, "expected type " + string.Join("|", allowed) + ", got " + actual);
}
if (schema.TryGetProperty("enum", out var ev))
{
int count = ev.ValueKind == JsonValueKind.Array ? ev.GetArrayLength() : 0;
bool found = false;
if (ev.ValueKind == JsonValueKind.Array)
foreach (var e in ev.EnumerateArray())
if (DeepEqual(v, e)) { found = true; break; }
if (!found) Issue(issues, path, "value not in enum (" + count + " allowed)");
}
if (schema.TryGetProperty("const", out var cv) && !DeepEqual(v, cv))
Issue(issues, path, "value does not match const");
if (v.ValueKind == JsonValueKind.Number)
{
double n = v.GetDouble();
if (schema.TryGetProperty("minimum", out var m) && IsNum(m) && n < m.GetDouble())
Issue(issues, path, JsNum(n) + " is less than minimum " + JsNum(m.GetDouble()));
if (schema.TryGetProperty("maximum", out var m) && IsNum(m) && n > m.GetDouble())
Issue(issues, path, JsNum(n) + " is greater than maximum " + JsNum(m.GetDouble()));
if (schema.TryGetProperty("exclusiveMinimum", out var m) && IsNum(m) && n <= m.GetDouble())
Issue(issues, path, JsNum(n) + " is not greater than exclusiveMinimum " + JsNum(m.GetDouble()));
if (schema.TryGetProperty("exclusiveMaximum", out var m) && IsNum(m) && n >= m.GetDouble())
Issue(issues, path, JsNum(n) + " is not less than exclusiveMaximum " + JsNum(m.GetDouble()));
}
if (v.ValueKind == JsonValueKind.String)
{
string s = v.GetString();
int len = Utf16Len(s);
if (schema.TryGetProperty("minLength", out var m) && IsNum(m) && len < m.GetDouble())
Issue(issues, path, "string length " + len + " is less than minLength " + JsNum(m.GetDouble()));
if (schema.TryGetProperty("maxLength", out var m) && IsNum(m) && len > m.GetDouble())
Issue(issues, path, "string length " + len + " is greater than maxLength " + JsNum(m.GetDouble()));
if (schema.TryGetProperty("pattern", out var pv) && pv.ValueKind == JsonValueKind.String)
{
string p = pv.GetString();
Regex re = null;
try { re = new Regex(p, RegexOptions.ECMAScript); }
catch (ArgumentException) { }
if (re == null) Issue(issues, path, "invalid pattern in schema: " + p);
else if (!re.IsMatch(s)) Issue(issues, path, "string does not match pattern " + p);
}
}
if (v.ValueKind == JsonValueKind.Array)
{
int len = v.GetArrayLength();
if (schema.TryGetProperty("minItems", out var m) && IsNum(m) && len < m.GetDouble())
Issue(issues, path, "array length " + len + " is less than minItems " + JsNum(m.GetDouble()));
if (schema.TryGetProperty("maxItems", out var m) && IsNum(m) && len > m.GetDouble())
Issue(issues, path, "array length " + len + " is greater than maxItems " + JsNum(m.GetDouble()));
if (schema.TryGetProperty("uniqueItems", out var uv) && uv.ValueKind == JsonValueKind.True)
{
var items = v.EnumerateArray().ToArray();
for (int i = 0; i < items.Length; i++)
for (int j = i + 1; j < items.Length; j++)
if (DeepEqual(items[i], items[j]))
Issue(issues, path + "[" + j + "]", "duplicate item (same as index " + i + ")");
}
if (schema.TryGetProperty("items", out var iv))
{
int i = 0;
foreach (var item in v.EnumerateArray())
Validate(item, iv, path + "[" + i++ + "]", issues);
}
}
if (v.ValueKind == JsonValueKind.Object)
{
if (schema.TryGetProperty("required", out var rv) && rv.ValueKind == JsonValueKind.Array)
{
foreach (var rk in rv.EnumerateArray())
{
string key = JsString(rk);
if (!v.TryGetProperty(key, out var ignored))
Issue(issues, path, "missing required property \"" + key + "\"");
}
}
bool hasProps = schema.TryGetProperty("properties", out var props)
&& props.ValueKind == JsonValueKind.Object;
if (hasProps)
{
foreach (var p in props.EnumerateObject())
if (v.TryGetProperty(p.Name, out var val))
Validate(val, p.Value, path + "." + p.Name, issues);
}
if (schema.TryGetProperty("additionalProperties", out var av) && av.ValueKind == JsonValueKind.False)
{
foreach (var p in v.EnumerateObject())
{
bool known = hasProps && props.TryGetProperty(p.Name, out var ignored);
if (!known) Issue(issues, path + "." + p.Name, "additional property not allowed");
}
}
}
}
// Validate a JSON document (instanceRaw) against a schema (schemaRaw).
public static JsonSchemaValidateResult ValidateJsonSchema(string schemaRaw, string instanceRaw)
{
var res = new JsonSchemaValidateResult();
if (string.IsNullOrWhiteSpace(schemaRaw) || string.IsNullOrWhiteSpace(instanceRaw))
{
res.Error = "Both a schema and an instance are required";
return res;
}
JsonElement schema;
JsonElement instance;
try
{
using var doc = JsonDocument.Parse(schemaRaw, new JsonDocumentOptions { MaxDepth = 1024 });
schema = doc.RootElement.Clone();
}
catch (JsonException e)
{
res.Error = "Schema: " + (string.IsNullOrEmpty(e.Message) ? "Invalid JSON" : e.Message);
return res;
}
try
{
using var doc = JsonDocument.Parse(instanceRaw, new JsonDocumentOptions { MaxDepth = 1024 });
instance = doc.RootElement.Clone();
}
catch (JsonException e)
{
res.Error = "Instance: " + (string.IsNullOrEmpty(e.Message) ? "Invalid JSON" : e.Message);
return res;
}
var issues = new List<ValidationIssue>();
Validate(instance, schema, "$", issues);
res.Valid = issues.Count == 0;
res.Issues = issues;
return res;
}
}
// Example:
// Validator.ValidateJsonSchema(
// "{\"type\":\"object\",\"required\":[\"port\"],\"properties\":{\"port\":{\"type\":\"integer\",\"minimum\":1024}}}",
// "{\"port\":80}").Issues
// → [{ Path = "$.port", Message = "80 is less than minimum 1024" }]
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 →