Repository navigation
feat(zod): add @length validation for Bytes
#2893
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from all commits
f3d5154
2b0c211
800bd6f
d0c11a5
da6d8ef
e94d410
1106d08
e55697c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -282,6 +282,33 @@ export function addDecimalValidation( | |
| return result; | ||
| } | ||
|
|
||
| export function addBytesValidation( | ||
| schema: z.ZodType<Uint8Array>, | ||
| attributes: readonly AttributeApplication[] | undefined, | ||
| ): z.ZodSchema { | ||
| if (!attributes || attributes.length === 0) { | ||
| return schema; | ||
| } | ||
|
|
||
| let result = schema; | ||
| for (const attr of attributes) { | ||
| switch (attr.name) { | ||
| case '@length': { | ||
| const min = getArgValue<number>(attr.args?.find((a) => a.name === 'min')?.value); | ||
| if (min !== undefined) { | ||
| result = result.refine((data) => data.length >= min); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pass the configured If a Bytes field declares
|
||
| } | ||
| const max = getArgValue<number>(attr.args?.find((a) => a.name === 'max')?.value); | ||
| if (max !== undefined) { | ||
| result = result.refine((data) => data.length <= max); | ||
| } | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| export function addListValidation( | ||
| schema: z.ZodArray<any>, | ||
| attributes: readonly AttributeApplication[] | undefined, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keep list
@lengthoff individual Bytes values.For a
Bytes[]field with@length(3, 5),getItemAttributespasses that attribute to each item. This new call then requires every byte value to contain 3–5 bytes, even though the constraint applies to the number of list items. The create and update builders already applyaddListValidationto the list. Exclude the list-level@lengthattribute from the item schema so a valid list can contain byte values of other lengths.