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
5 changes: 5 additions & 0 deletions .changeset/upgrade-zod-v4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@felte/validator-zod': major
---

BREAKING: upgrade Zod peer dependency to v4. Zod v3 schemas are no longer supported; update imports to use `ZodType` instead of `ZodSchema` and replace `.nonempty()` with `.min(1)`.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"vite-plugin-solid": "^2.7.0",
"vitest": "^2.1.4",
"yup": "^1.2.0",
"zod": "^1.11.13"
"zod": "^4.4.3"
},
"volta": {
"node": "22.10.0"
Expand Down
26 changes: 12 additions & 14 deletions packages/validator-zod/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ import { validator } from '@felte/validator-zod';
import { z } from 'zod';

const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
email: z.string().email().min(1),
password: z.string().min(1),
});

const { form } = createForm({
Expand All @@ -44,8 +44,8 @@ import { validateSchema } from '@felte/validator-zod';
import { z } from 'zod';

const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
email: z.string().email().min(1),
password: z.string().min(1),
});

const { form } = createForm({
Expand All @@ -64,17 +64,15 @@ import { validator } from '@felte/validator-zod';
import { z } from 'zod';

const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
email: z.string().email().min(1),
password: z.string().min(1),
});

// We only warn if the user has started typing a value
const warnSchema = zod.object({
password: zod
.string()
.refine((value) => (value ? value.length > 8 : true), {
message: 'Password is not secure',
}),
const warnSchema = z.object({
password: z.string().refine((value) => (value ? value.length > 8 : true), {
message: 'Password is not secure',
}),
});

const { form } = createForm({
Expand All @@ -95,8 +93,8 @@ Zod allows you to infer the type of your schema using `z.infer`. This can be use
import { z } from 'zod';

const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
email: z.string().email().min(1),
password: z.string().min(1),
});

const { form } = createForm<z.infer<typeof schema>>(/* ... */);
Expand Down
4 changes: 2 additions & 2 deletions packages/validator-zod/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@
"@felte/core": "workspace:*",
"felte": "workspace:*",
"svelte": "^3.46.4",
"zod": "^3.2.0"
"zod": "^4.4.3"
},
"peerDependencies": {
"zod": "^3.2.0"
"zod": "^4.0.0"
},
"publishConfig": {
"access": "public"
Expand Down
31 changes: 18 additions & 13 deletions packages/validator-zod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,30 @@ import type {
Extender,
} from '@felte/common';
import { _update } from '@felte/common';
import type { ZodError, ZodSchema } from 'zod';
import type { ZodError, ZodType } from 'zod';

export type ValidatorConfig<Data extends Obj = Obj> = {
schema: ZodSchema<Data>;
export type ValidatorConfig = {
schema: ZodType;
level?: 'error' | 'warning';
};

export function validateSchema<Data extends Obj>(
schema: ZodSchema
schema: ZodType,
): ValidationFunction<Data> {
function walk(
error: ZodError,
err: AssignableErrors<Data>
issues: ZodError['issues'],
err: AssignableErrors<Data>,
): AssignableErrors<Data> {
for (const issue of error.issues) {
if (issue.code === 'invalid_union') {
for (const unionError of issue.unionErrors) {
err = walk(unionError, err);
for (const issue of issues) {
if (issue.code === 'invalid_union' && issue.errors.length) {
for (const optionIssues of issue.errors) {
err = walk(optionIssues, err);
}
} else if (
issue.code === 'invalid_key' ||
issue.code === 'invalid_element'
) {
err = walk(issue.issues, err);
} else {
if (!issue.path) continue;

Expand All @@ -43,12 +48,12 @@ export function validateSchema<Data extends Obj>(
}

return async function validate(
values: Data
values: Data,
): Promise<AssignableErrors<Data> | undefined> {
const result = await schema.safeParseAsync(values);
if (!result.success) {
let err = {} as AssignableErrors<Data>;
err = walk(result.error, err);
err = walk(result.error.issues, err);
return err;
}
};
Expand All @@ -59,7 +64,7 @@ export function validator<Data extends Obj = Obj>({
level = 'error',
}: ValidatorConfig): Extender<Data> {
return function extender(
currentForm: CurrentForm<Data>
currentForm: CurrentForm<Data>,
): ExtenderHandler<Data> {
if (currentForm.stage !== 'SETUP') return {};
const validateFn = validateSchema<Data>(schema);
Expand Down
51 changes: 29 additions & 22 deletions packages/validator-zod/tests/validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ import '@testing-library/jest-dom/vitest';
import { expect, describe, test, vi } from 'vitest';
import { createForm } from './common';
import { validateSchema, validator } from '../src';
import { z, ZodSchema } from 'zod';
import { z, ZodType } from 'zod';
import { get } from 'svelte/store';

type Data = {
email: string;
password: string;
};

const ZOD_EMAIL_ERROR = 'Invalid email address';
const ZOD_MIN_ERROR = 'Too small: expected string to have >=1 characters';

describe('Validator zod', () => {
test('correctly validates', async () => {
const schema = z.object({
Expand All @@ -30,8 +33,8 @@ describe('Validator zod', () => {

expect(get(data)).to.deep.equal(mockData);
expect(get(errors)).to.deep.equal({
email: ['Invalid email', 'String must contain at least 1 character(s)'],
password: ['String must contain at least 1 character(s)'],
email: [ZOD_EMAIL_ERROR, ZOD_MIN_ERROR],
password: [ZOD_MIN_ERROR],
});

data.set({
Expand Down Expand Up @@ -71,8 +74,8 @@ describe('Validator zod', () => {
expect(get(data)).to.deep.equal(mockData);
expect(get(errors)).to.deep.equal({
account: {
email: ['Invalid email', 'String must contain at least 1 character(s)'],
password: ['String must contain at least 1 character(s)'],
email: [ZOD_EMAIL_ERROR, ZOD_MIN_ERROR],
password: [ZOD_MIN_ERROR],
},
});

Expand Down Expand Up @@ -122,8 +125,8 @@ describe('Validator zod', () => {

expect(get(data)).to.deep.equal(mockData);
expect(get(errors)).to.deep.equal({
email: ['Invalid email', 'String must contain at least 1 character(s)'],
password: ['String must contain at least 1 character(s)'],
email: [ZOD_EMAIL_ERROR, ZOD_MIN_ERROR],
password: [ZOD_MIN_ERROR],
});
expect(get(warnings)).to.deep.equal({
email: null,
Expand Down Expand Up @@ -171,8 +174,8 @@ describe('Validator zod', () => {
expect(get(data)).to.deep.equal(mockData);
expect(get(errors)).to.deep.equal({
account: {
email: ['Invalid email', 'String must contain at least 1 character(s)'],
password: ['String must contain at least 1 character(s)'],
email: [ZOD_EMAIL_ERROR, ZOD_MIN_ERROR],
password: [ZOD_MIN_ERROR],
},
});

Expand Down Expand Up @@ -222,12 +225,8 @@ describe('Validator zod', () => {
expect(get(data)).to.deep.equal(mockData);
expect(get(errors)).to.deep.equal({
account: {
email: [
'not an email',
'Invalid email',
'String must contain at least 1 character(s)',
],
password: ['String must contain at least 1 character(s)'],
email: ['not an email', ZOD_EMAIL_ERROR, ZOD_MIN_ERROR],
password: [ZOD_MIN_ERROR],
},
});

Expand Down Expand Up @@ -326,7 +325,7 @@ describe('Validator zod', () => {
});

test('should surface union type errors', async () => {
async function t(schema: ZodSchema, initialValues: object) {
async function t(schema: ZodType, initialValues: object) {
const { validate, errors } = createForm({
initialValues,
extend: validator({ schema }),
Expand All @@ -338,14 +337,20 @@ describe('Validator zod', () => {
const schema = z.object({ foo: z.string().min(1) });
const data = { foo: '' };

const unionErrors = await t(z.union([schema, schema]), data);
const errors = await t(schema, data);
const unionErrors = await t(
z.union([schema, z.object({ foo: z.string().min(2) })]),
data,
);

expect(unionErrors).to.deep.equal(errors);
expect(errors).to.deep.equal({ foo: [ZOD_MIN_ERROR] });
expect(unionErrors).to.deep.equal({
foo: [ZOD_MIN_ERROR, 'Too small: expected string to have >=2 characters'],
});
});

test('should surface discriminatedUnion type errors', async () => {
async function t(schema: ZodSchema, initialValues: object) {
async function t(schema: ZodType, initialValues: object) {
const { validate, errors } = createForm({
initialValues,
extend: validator({ schema }),
Expand All @@ -356,11 +361,13 @@ describe('Validator zod', () => {

const schema = z.discriminatedUnion('type', [
z.object({ type: z.literal('foo'), foo: z.string().min(1) }),
z.object({ type: z.literal('bar'), bar: z.string().min(1) })
], { errorMap: () => ({ message: 'Oops' }) });
z.object({ type: z.literal('bar'), bar: z.string().min(1) }),
]);

const errors = await t(schema, { type: 'baz' });

expect(errors).to.deep.equal({ type: ['Oops'] });
expect(errors).to.deep.equal({
type: ["Invalid discriminator value. Expected 'foo' | 'bar'"],
});
});
});
18 changes: 9 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.