Skip to content

Commit 50d76e2

Browse files
committed
Add an object Validator
1 parent 6a62e99 commit 50d76e2

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

‎src/json/index.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,24 @@ test("validateSchema - validates arrays", async (t) => {
8585
t.false(json.validateSchema(arraySchema, { arrayKey: [4, 8, 15, null] }));
8686
});
8787

88+
const objectSchema = {
89+
objectKey: json.object(arraySchema),
90+
};
91+
92+
test("validateSchema - validates objects", async (t) => {
93+
// Objects of the given schema are accepted.
94+
t.true(json.validateSchema(objectSchema, { objectKey: { arrayKey: [] } }));
95+
t.true(json.validateSchema(objectSchema, { objectKey: { arrayKey: [4] } }));
96+
97+
// Other values are not accepted.
98+
t.false(json.validateSchema(objectSchema, {}));
99+
t.false(json.validateSchema(objectSchema, { objectKey: [] }));
100+
t.false(json.validateSchema(objectSchema, { objectKey: undefined }));
101+
t.false(json.validateSchema(objectSchema, { objectKey: null }));
102+
t.false(json.validateSchema(objectSchema, { objectKey: "foo" }));
103+
t.false(json.validateSchema(objectSchema, { objectKey: 123 }));
104+
});
105+
88106
test("validateSchema - checkSchema reports unknown keys", async (t) => {
89107
const result = json.checkSchema(testSchema, {
90108
requiredKey: "foo",

‎src/json/index.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,16 @@ export function array<T>(validator: Validator<T>) {
7676
} as const satisfies Validator<T[]>;
7777
}
7878

79+
/** A validator for objects. */
80+
export function object(schema: Schema) {
81+
return {
82+
validate: (val: unknown) => {
83+
return isObject(val) && validateSchema(schema, val);
84+
},
85+
required: true,
86+
} as const satisfies Validator<FromSchema<typeof schema>>;
87+
}
88+
7989
/**
8090
* Transforms a validator to be optional, accepting `undefined` or `null` for an
8191
* absent value.

0 commit comments

Comments
 (0)