From 50d76e2fa3a057fbae009851a89d7a4b22309ee9 Mon Sep 17 00:00:00 2001 From: "Michael B. Gale" Date: Thu, 9 Jul 2026 23:42:28 +0100 Subject: [PATCH] Add an `object` `Validator` --- src/json/index.test.ts | 18 ++++++++++++++++++ src/json/index.ts | 10 ++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/json/index.test.ts b/src/json/index.test.ts index a238d8071..71f800003 100644 --- a/src/json/index.test.ts +++ b/src/json/index.test.ts @@ -85,6 +85,24 @@ test("validateSchema - validates arrays", async (t) => { t.false(json.validateSchema(arraySchema, { arrayKey: [4, 8, 15, null] })); }); +const objectSchema = { + objectKey: json.object(arraySchema), +}; + +test("validateSchema - validates objects", async (t) => { + // Objects of the given schema are accepted. + t.true(json.validateSchema(objectSchema, { objectKey: { arrayKey: [] } })); + t.true(json.validateSchema(objectSchema, { objectKey: { arrayKey: [4] } })); + + // Other values are not accepted. + t.false(json.validateSchema(objectSchema, {})); + t.false(json.validateSchema(objectSchema, { objectKey: [] })); + t.false(json.validateSchema(objectSchema, { objectKey: undefined })); + t.false(json.validateSchema(objectSchema, { objectKey: null })); + t.false(json.validateSchema(objectSchema, { objectKey: "foo" })); + t.false(json.validateSchema(objectSchema, { objectKey: 123 })); +}); + test("validateSchema - checkSchema reports unknown keys", async (t) => { const result = json.checkSchema(testSchema, { requiredKey: "foo", diff --git a/src/json/index.ts b/src/json/index.ts index e9fbbd8a7..083bd49bb 100644 --- a/src/json/index.ts +++ b/src/json/index.ts @@ -76,6 +76,16 @@ export function array(validator: Validator) { } as const satisfies Validator; } +/** A validator for objects. */ +export function object(schema: Schema) { + return { + validate: (val: unknown) => { + return isObject(val) && validateSchema(schema, val); + }, + required: true, + } as const satisfies Validator>; +} + /** * Transforms a validator to be optional, accepting `undefined` or `null` for an * absent value.