Sikari
Sikari
ZZod
Created by Maxiviper117 on 4/2/2025 in #questions
Maxiviper117 - I'm working on validating an obj...
Anyways, I hope that helps!
7 replies
ZZod
Created by Maxiviper117 on 4/2/2025 in #questions
Maxiviper117 - I'm working on validating an obj...
You might be able to swap the order of the schemas in the intersection, not sure if that would work. Alternatively, you could extract the known schema to a variable and exclude that way:
const knownKeysSchema = z.object({
knownKey: z.string(),
});

const schema = z.intersection(
z
.record(z.string())
.superRefine((obj, ctx): obj is ObjectWithMetaFields => {
const keys = Object.keys(obj).filter((x) => !(x in knownKeysSchema.shape));
const invalidKeys = keys.filter((x) => metaFieldRegex.test(x) === false);

if (invalidKeys.length > 0) {
ctx.addIssue({
fatal: true,
code: "unrecognized_keys",
keys: invalidKeys,
message: `Meta fields must match the regex: ${metaFieldRegex.source}`,
});
}

return z.NEVER;
}),
z.object({
knownKey: z.string(),
}),
);
const knownKeysSchema = z.object({
knownKey: z.string(),
});

const schema = z.intersection(
z
.record(z.string())
.superRefine((obj, ctx): obj is ObjectWithMetaFields => {
const keys = Object.keys(obj).filter((x) => !(x in knownKeysSchema.shape));
const invalidKeys = keys.filter((x) => metaFieldRegex.test(x) === false);

if (invalidKeys.length > 0) {
ctx.addIssue({
fatal: true,
code: "unrecognized_keys",
keys: invalidKeys,
message: `Meta fields must match the regex: ${metaFieldRegex.source}`,
});
}

return z.NEVER;
}),
z.object({
knownKey: z.string(),
}),
);
7 replies
ZZod
Created by Maxiviper117 on 4/2/2025 in #questions
Maxiviper117 - I'm working on validating an obj...
If you wish to get more type safety, here is something: https://tsplay.dev/N5oVdW
7 replies
ZZod
Created by Maxiviper117 on 4/2/2025 in #questions
Maxiviper117 - I'm working on validating an obj...
You would intersect your known object with the "unknown" record just like in pure types. Here's a playground for one of the implementations: https://tsplay.dev/ND9Ajm
7 replies
ZZod
Created by Gludek on 5/11/2024 in #questions
Gludek - Just to confirm z.string().email() can...
Perhaps you're looking for:
const schema = z.literal("").or(z.string().email());
const schema = z.literal("").or(z.string().email());
8 replies
ZZod
Created by Gludek on 5/11/2024 in #questions
Gludek - Just to confirm z.string().email() can...
Your form most likely is not passing null or undefined, most likely you have ""
8 replies