Add an object Validator

This commit is contained in:
Michael B. Gale
2026-07-09 23:42:28 +01:00
parent 1f91ec8f3c
commit 98dbd66eae
2 changed files with 28 additions and 0 deletions

View File

@@ -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",

View File

@@ -76,6 +76,16 @@ export function array<T>(validator: Validator<T>) {
} as const satisfies Validator<T[]>;
}
/** 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<FromSchema<typeof schema>>;
}
/**
* Transforms a validator to be optional, accepting `undefined` or `null` for an
* absent value.