Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/zod/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { partialSafeParse, PartialSafeParseResult, RecursivePartial } from './partial-safe-parse.js';
export { StringyIntegerSchema } from './stringy-integer-schema.js';
23 changes: 23 additions & 0 deletions src/zod/stringy-integer-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { z } from 'zod';

/**
* This validates the string is a plain non-negative integer and converts it to a `number`.
* - Also rejects values that would lose precision past `Number.MAX_SAFE_INTEGER`
*/
export const StringyIntegerSchema = z
.string()
.regex(/^\d+$/, {
error: (issue) => `Invalid input: expected numeric string, received ${JSON.stringify(issue.input)}`,
})
.transform((value, ctx) => {
const number = Number(value);
if (Number.isSafeInteger(number)) return number;

ctx.addIssue({
code: 'custom',
message:
`Invalid input: stringy integer "${value}" exceeds Number.MAX_SAFE_INTEGER and would lose precision` +
' - use z.string() for this field instead',
});
return z.NEVER;
});
34 changes: 34 additions & 0 deletions test/zod/stringy-integer-schema.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { assert, describe, expect, it } from 'vitest';

import { StringyIntegerSchema } from '../../src/zod/stringy-integer-schema.js';

describe('StringyIntegerSchema', () => {
it('should validate and transform stringy integers correctly', () => {
// Act
const result = StringyIntegerSchema.parse('123');

// Assert
expect(result).toBe(123);
});

it('should throw an error for invalid stringy integers', () => {
// Act
const result = StringyIntegerSchema.safeParse('abc');

// Assert
assert(result.error);
expect(result.error.issues[0].message).toStrictEqual('Invalid input: expected numeric string, received "abc"');
});

it('should throw an error for number over the maximum safe integer', () => {
// Act
const result = StringyIntegerSchema.safeParse('9007199254740992'); // Number.MAX_SAFE_INTEGER + 1

// Assert
assert(result.error);
expect(result.error.issues[0].message).toStrictEqual(
'Invalid input: stringy integer "9007199254740992" exceeds Number.MAX_SAFE_INTEGER and would lose ' +
'precision - use z.string() for this field instead',
);
});
});
Loading