From fbdb02a28d3c5255b3d7e5dcfd04b82d36708323 Mon Sep 17 00:00:00 2001 From: Himanshu Rai Date: Mon, 17 Mar 2025 15:35:10 +0530 Subject: [PATCH] Fix required tag interpretation for map fields By default map fields are considered nullable. With 'required', they are not nullable but can be empty. But the current implementation enforced 'required' maps to be non-empty. --- zod.go | 2 -- zod_test.go | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/zod.go b/zod.go index 9e56a2d..e339241 100644 --- a/zod.go +++ b/zod.go @@ -576,7 +576,6 @@ forParts: } else { if valValue != "" { switch valName { - case "required": case "min": validateStr.WriteString(fmt.Sprintf(".min(%s)", valValue)) case "max": @@ -713,7 +712,6 @@ forParts: switch valName { case "omitempty": case "required": - refines = append(refines, ".refine((val) => Object.keys(val).length > 0, 'Empty map')") case "dive": break forParts diff --git a/zod_test.go b/zod_test.go index 9604260..e112627 100644 --- a/zod_test.go +++ b/zod_test.go @@ -1330,7 +1330,7 @@ func TestMapWithValidations(t *testing.T) { } assert.Equal(t, `export const RequiredSchema = z.object({ - Map: z.record(z.string(), z.string()).refine((val) => Object.keys(val).length > 0, 'Empty map'), + Map: z.record(z.string(), z.string()), }) export type Required = z.infer @@ -1720,7 +1720,7 @@ export const UserSchema = z.object({ PostOptional: PostSchema.optional(), PostOptionalNullable: PostSchema.optional().nullable(), Metadata: z.record(z.string(), z.string()).nullable(), - MetadataLength: z.record(z.string(), z.string()).refine((val) => Object.keys(val).length > 0, 'Empty map').refine((val) => Object.keys(val).length >= 1, 'Map too small').refine((val) => Object.keys(val).length <= 10, 'Map too large'), + MetadataLength: z.record(z.string(), z.string()).refine((val) => Object.keys(val).length >= 1, 'Map too small').refine((val) => Object.keys(val).length <= 10, 'Map too large'), MetadataOptional: z.record(z.string(), z.string()).optional(), MetadataOptionalNullable: z.record(z.string(), z.string()).optional().nullable(), ExtendedProps: z.any(),