@hookform/resolvers 5.0.1 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +17 -16
  2. package/package.json +2 -2
  3. package/standard-schema/src/__tests__/__fixtures__/data.ts +1 -1
  4. package/standard-schema/src/__tests__/standard-schema.ts +1 -1
  5. package/typebox/src/__tests__/typebox.ts +2 -2
  6. package/typeschema/dist/typeschema.d.ts +1 -1
  7. package/typeschema/dist/typeschema.js.map +1 -1
  8. package/typeschema/dist/typeschema.modern.mjs.map +1 -1
  9. package/typeschema/dist/typeschema.module.js.map +1 -1
  10. package/typeschema/dist/typeschema.umd.js.map +1 -1
  11. package/typeschema/src/__tests__/Form-native-validation.tsx +1 -1
  12. package/typeschema/src/__tests__/Form.tsx +1 -1
  13. package/typeschema/src/__tests__/__fixtures__/data.ts +1 -1
  14. package/typeschema/src/__tests__/typeschema.ts +1 -1
  15. package/typeschema/src/typeschema.ts +1 -1
  16. package/zod/dist/zod.d.ts +46 -7
  17. package/zod/dist/zod.js +1 -1
  18. package/zod/dist/zod.js.map +1 -1
  19. package/zod/dist/zod.mjs +1 -1
  20. package/zod/dist/zod.modern.mjs +1 -1
  21. package/zod/dist/zod.modern.mjs.map +1 -1
  22. package/zod/dist/zod.module.js +1 -1
  23. package/zod/dist/zod.module.js.map +1 -1
  24. package/zod/dist/zod.umd.js +1 -1
  25. package/zod/dist/zod.umd.js.map +1 -1
  26. package/zod/package.json +2 -1
  27. package/zod/src/__tests__/Form-native-validation.tsx +1 -1
  28. package/zod/src/__tests__/Form.tsx +1 -1
  29. package/zod/src/__tests__/__fixtures__/{data.ts → data-v3.ts} +1 -1
  30. package/zod/src/__tests__/__fixtures__/data-v4-mini.ts +98 -0
  31. package/zod/src/__tests__/__fixtures__/data-v4.ts +89 -0
  32. package/zod/src/__tests__/zod-v3.ts +178 -0
  33. package/zod/src/__tests__/zod-v4-mini.ts +182 -0
  34. package/zod/src/__tests__/{zod.ts → zod-v4.ts} +17 -2
  35. package/zod/src/zod.ts +227 -53
@@ -1 +1 @@
1
- {"version":3,"file":"zod.umd.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\nimport { ZodError, z } from 'zod';\n\nconst isZodError = (error: any): error is ZodError =>\n Array.isArray(error?.errors);\n\nfunction parseErrorSchema(\n zodErrors: z.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n const unionError = error.unionErrors[0].errors[0];\n\n errors[_path] = {\n message: unionError.message,\n type: unionError.code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: z.ZodSchema<Output, any, Input>,\n schemaOptions?: Partial<z.ParseParams>,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver<Input, Context, Output>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: z.ZodSchema<Output, any, Input>,\n schemaOptions: Partial<z.ParseParams> | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver<Input, Context, Input>;\n\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z.object({\n * name: z.string().min(2),\n * age: z.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: z.ZodSchema<Output, any, Input>,\n schemaOptions?: Partial<z.ParseParams>,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZodError(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n}\n"],"names":["parseErrorSchema","zodErrors","validateAllFieldCriteria","errors","length","error","code","message","_path","path","join","unionError","unionErrors","type","forEach","e","push","types","messages","appendErrors","concat","shift","schema","schemaOptions","resolverOptions","values","_","options","Promise","resolve","mode","then","data","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign","_catch","Array","isArray","isZodError","toNestErrors","criteriaMode","re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MC,QAAa,MAALnC,OAAK,EAALA,EAAOF,OAAO,CA8GpBsC,CAAWpC,GACb,MAAO,CACLoB,OAAQ,CAAA,EACRtB,OAAQuC,EAAYA,aAClB1C,EACEK,EAAMF,QACLwB,EAAQM,2BACkB,QAAzBN,EAAQgB,cAEZhB,IAKN,MAAMtB,CACR,GACF,CAAC,MAAAU,GAAAa,OAAAA,QAAAgB,OAAA7B,EACH,CAAA,CAAA"}
1
+ {"version":3,"file":"zod.umd.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n return (\n '_def' in schema &&\n typeof schema._def === 'object' &&\n 'typeName' in schema._def\n );\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // instanceof is safe in Zod 4 (uses Symbol.hasInstance)\n return error instanceof z4.$ZodError;\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n const unionError = error.unionErrors[0].errors[0];\n\n errors[_path] = {\n message: unionError.message,\n type: unionError.code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union') {\n const unionError = error.errors[0][0];\n\n errors[_path] = {\n message: unionError.message,\n type: unionError.code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: {\n typeName: string;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>,\n>(\n schema: z4.$ZodType<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const parseFn =\n resolverOptions.mode === 'sync' ? z4.parse : z4.parseAsync;\n const data: any = await parseFn(schema, values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","length","error","code","message","_path","path","join","unionError","unionErrors","type","forEach","e","push","types","messages","appendErrors","concat","shift","parseZod4Issues","schema","schemaOptions","resolverOptions","_def","isZod3Schema","values","_","options","Promise","resolve","_catch","mode","then","data","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign","Array","isArray","issues","isZod3Error","toNestErrors","criteriaMode","reject","_zod","isZod4Schema","z4","parse","parseAsync","$ZodError","isZod4Error","Error"],"mappings":"iyBA+BA,SAASA,EACPC,EACAC,GAGA,IADA,IAAMC,EAAqC,CAAE,EACtCF,EAAUG,QAAU,CACzB,IAAMC,EAAQJ,EAAU,GAChBK,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,KAExB,IAAKP,EAAOK,GACV,GAAI,gBAAiBH,EAAO,CAC1B,IAAMM,EAAaN,EAAMO,YAAY,GAAGT,OAAO,GAE/CA,EAAOK,GAAS,CACdD,QAASI,EAAWJ,QACpBM,KAAMF,EAAWL,KAErB,MACEH,EAAOK,GAAS,CAAED,QAAAA,EAASM,KAAMP,GAUrC,GANI,gBAAiBD,GACnBA,EAAMO,YAAYE,QAAQ,SAACH,GAAU,OACnCA,EAAWR,OAAOW,QAAQ,SAACC,GAAC,OAAKd,EAAUe,KAAKD,EAAE,EAAC,GAInDb,EAA0B,CAC5B,IAAMe,EAAQd,EAAOK,GAAOS,MACtBC,EAAWD,GAASA,EAAMZ,EAAMC,MAEtCH,EAAOK,GAASW,EAAYA,aAC1BX,EACAN,EACAC,EACAG,EACAY,EACK,GAAgBE,OAAOF,EAAsBb,EAAME,SACpDF,EAAME,QAEd,CAEAN,EAAUoB,OACZ,CAEA,OAAOlB,CACT,CAEA,SAASmB,EACPrB,EACAC,GAIA,IAFA,IAAMC,EAAqC,CAAA,EAEpCF,EAAUG,QAAU,CACzB,IAAMC,EAAQJ,EAAU,GAChBK,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,K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,EACVzB,OAAQ2C,EAAYA,aAClB9C,EACEK,EAAMF,QACL2B,EAAQO,2BACkB,QAAzBP,EAAQiB,cAEZjB,IAKN,MAAMzB,CACR,GACF,CAAC,MAAAU,GAAA,OAAAgB,QAAAiB,OAAAjC,EAAA,CAAA,EAGH,GA5PmB,SAACQ,GACpB,MAAO,SAAUA,GAAiC,iBAAhBA,EAAO0B,IAC3C,CA0PMC,CAAa3B,GACf,OAAcK,SAAAA,EAAeC,EAAGC,GAAO,IAAIC,OAAAA,QAAAC,QAAAC,EACrC,WAE2D,OAAAF,QAAAC,SAAlC,SAAzBP,EAAgBS,KAAkBiB,EAAGC,MAAQD,EAAGE,YAClB9B,EAAQK,EAAQJ,IAAcW,KAAxDC,SAAAA,GAKN,OAHAN,EAAQO,2BACNC,EAAsBA,uBAAC,CAAE,EAAER,GAEtB,CACL3B,OAAQ,CAAA,EACRyB,OAAQH,EAAgBc,IAAMC,OAAOC,OAAO,CAAE,EAAEb,GAAUQ,EAChB,EAC9C,EAAS/B,SAAAA,GACP,GA/QY,SAACA,GAEnB,OAAOA,aAAiB8C,EAAGG,SAC7B,CA4QYC,CAAYlD,GACd,MAAO,CACLuB,OAAQ,CAAE,EACVzB,OAAQ2C,EAAYA,aAClBxB,EACEjB,EAAMuC,QACLd,EAAQO,2BACkB,QAAzBP,EAAQiB,cAEZjB,IAKN,MAAMzB,CACR,GACF,CAAC,MAAAU,GAAAgB,OAAAA,QAAAiB,OAAAjC,EACH,CAAA,EAEA,MAAM,IAAIyC,MAAM,kCAClB"}
package/zod/package.json CHANGED
@@ -12,6 +12,7 @@
12
12
  "license": "MIT",
13
13
  "peerDependencies": {
14
14
  "react-hook-form": "^7.55.0",
15
- "@hookform/resolvers": "^2.0.0"
15
+ "@hookform/resolvers": "^2.0.0",
16
+ "zod": "^3.25.0"
16
17
  }
17
18
  }
@@ -2,7 +2,7 @@ import { render, screen } from '@testing-library/react';
2
2
  import user from '@testing-library/user-event';
3
3
  import React from 'react';
4
4
  import { useForm } from 'react-hook-form';
5
- import { z } from 'zod';
5
+ import { z } from 'zod/v3';
6
6
  import { zodResolver } from '..';
7
7
 
8
8
  const USERNAME_REQUIRED_MESSAGE = 'username field is required';
@@ -2,7 +2,7 @@ import { render, screen } from '@testing-library/react';
2
2
  import user from '@testing-library/user-event';
3
3
  import React from 'react';
4
4
  import { useForm } from 'react-hook-form';
5
- import { z } from 'zod';
5
+ import { z } from 'zod/v3';
6
6
  import { zodResolver } from '..';
7
7
 
8
8
  const schema = z.object({
@@ -1,5 +1,5 @@
1
1
  import { Field, InternalFieldName } from 'react-hook-form';
2
- import { z } from 'zod';
2
+ import { z } from 'zod/v3';
3
3
 
4
4
  export const schema = z
5
5
  .object({
@@ -0,0 +1,98 @@
1
+ import { Field, InternalFieldName } from 'react-hook-form';
2
+ import { z } from 'zod/v4-mini';
3
+
4
+ export const schema = z
5
+ .object({
6
+ username: z
7
+ .string()
8
+ .check(z.regex(/^\w+$/), z.minLength(3), z.maxLength(30)),
9
+ password: z
10
+ .string()
11
+ .check(
12
+ z.regex(new RegExp('.*[A-Z].*'), 'One uppercase character'),
13
+ z.regex(new RegExp('.*[a-z].*'), 'One lowercase character'),
14
+ z.regex(new RegExp('.*\\d.*'), 'One number'),
15
+ z.regex(
16
+ new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
17
+ 'One special character',
18
+ ),
19
+ z.minLength(8, 'Must be at least 8 characters in length'),
20
+ ),
21
+ repeatPassword: z.string(),
22
+ accessToken: z.union([z.string(), z.number()]),
23
+ birthYear: z.optional(z.number().check(z.minimum(1900), z.maximum(2013))),
24
+ email: z.optional(z.email()),
25
+ tags: z.array(z.string()),
26
+ enabled: z.boolean(),
27
+ url: z.union([z.url('Custom error url'), z.literal('')]),
28
+ like: z.optional(
29
+ z.array(
30
+ z.object({
31
+ id: z.number(),
32
+ name: z.string().check(z.length(4)),
33
+ }),
34
+ ),
35
+ ),
36
+ dateStr: z
37
+ .pipe(
38
+ z.string(),
39
+ z.transform((value) => new Date(value)),
40
+ )
41
+ .check(
42
+ z.refine((value) => !isNaN(value.getTime()), {
43
+ message: 'Invalid date',
44
+ }),
45
+ ),
46
+ })
47
+ .check(
48
+ z.refine((obj) => obj.password === obj.repeatPassword, {
49
+ message: 'Passwords do not match',
50
+ path: ['confirm'],
51
+ }),
52
+ );
53
+
54
+ export const validData = {
55
+ username: 'Doe',
56
+ password: 'Password123_',
57
+ repeatPassword: 'Password123_',
58
+ birthYear: 2000,
59
+ email: 'john@doe.com',
60
+ tags: ['tag1', 'tag2'],
61
+ enabled: true,
62
+ accessToken: 'accessToken',
63
+ url: 'https://react-hook-form.com/',
64
+ like: [
65
+ {
66
+ id: 1,
67
+ name: 'name',
68
+ },
69
+ ],
70
+ dateStr: '2020-01-01',
71
+ } satisfies z.input<typeof schema>;
72
+
73
+ export const invalidData = {
74
+ password: '___',
75
+ email: '',
76
+ birthYear: 'birthYear',
77
+ like: [{ id: 'z' }],
78
+ url: 'abc',
79
+ } as unknown as z.input<typeof schema>;
80
+
81
+ export const fields: Record<InternalFieldName, Field['_f']> = {
82
+ username: {
83
+ ref: { name: 'username' },
84
+ name: 'username',
85
+ },
86
+ password: {
87
+ ref: { name: 'password' },
88
+ name: 'password',
89
+ },
90
+ email: {
91
+ ref: { name: 'email' },
92
+ name: 'email',
93
+ },
94
+ birthday: {
95
+ ref: { name: 'birthday' },
96
+ name: 'birthday',
97
+ },
98
+ };
@@ -0,0 +1,89 @@
1
+ import { Field, InternalFieldName } from 'react-hook-form';
2
+ import { z } from 'zod/v4';
3
+
4
+ export const schema = z
5
+ .object({
6
+ username: z.string().regex(/^\w+$/).min(3).max(30),
7
+ password: z
8
+ .string()
9
+ .regex(new RegExp('.*[A-Z].*'), 'One uppercase character')
10
+ .regex(new RegExp('.*[a-z].*'), 'One lowercase character')
11
+ .regex(new RegExp('.*\\d.*'), 'One number')
12
+ .regex(
13
+ new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
14
+ 'One special character',
15
+ )
16
+ .min(8, 'Must be at least 8 characters in length'),
17
+ repeatPassword: z.string(),
18
+ accessToken: z.union([z.string(), z.number()]),
19
+ birthYear: z.number().min(1900).max(2013).optional(),
20
+ email: z.string().email().optional(),
21
+ tags: z.array(z.string()),
22
+
23
+ enabled: z.boolean(),
24
+ url: z.string().url('Custom error url').or(z.literal('')),
25
+ like: z
26
+ .array(
27
+ z.object({
28
+ id: z.number(),
29
+ name: z.string().length(4),
30
+ }),
31
+ )
32
+ .optional(),
33
+ dateStr: z
34
+ .string()
35
+ .transform((value) => new Date(value))
36
+ .refine((value) => !isNaN(value.getTime()), {
37
+ message: 'Invalid date',
38
+ }),
39
+ })
40
+ .refine((obj) => obj.password === obj.repeatPassword, {
41
+ message: 'Passwords do not match',
42
+ path: ['confirm'],
43
+ });
44
+
45
+ export const validData = {
46
+ username: 'Doe',
47
+ password: 'Password123_',
48
+ repeatPassword: 'Password123_',
49
+ birthYear: 2000,
50
+ email: 'john@doe.com',
51
+ tags: ['tag1', 'tag2'],
52
+ enabled: true,
53
+ accessToken: 'accessToken',
54
+ url: 'https://react-hook-form.com/',
55
+ like: [
56
+ {
57
+ id: 1,
58
+ name: 'name',
59
+ },
60
+ ],
61
+ dateStr: '2020-01-01',
62
+ } satisfies z.input<typeof schema>;
63
+
64
+ export const invalidData = {
65
+ password: '___',
66
+ email: '',
67
+ birthYear: 'birthYear',
68
+ like: [{ id: 'z' }],
69
+ url: 'abc',
70
+ } as unknown as z.input<typeof schema>;
71
+
72
+ export const fields: Record<InternalFieldName, Field['_f']> = {
73
+ username: {
74
+ ref: { name: 'username' },
75
+ name: 'username',
76
+ },
77
+ password: {
78
+ ref: { name: 'password' },
79
+ name: 'password',
80
+ },
81
+ email: {
82
+ ref: { name: 'email' },
83
+ name: 'email',
84
+ },
85
+ birthday: {
86
+ ref: { name: 'birthday' },
87
+ name: 'birthday',
88
+ },
89
+ };
@@ -0,0 +1,178 @@
1
+ import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
2
+ import { z } from 'zod/v3';
3
+ import { zodResolver } from '..';
4
+ import { fields, invalidData, schema, validData } from './__fixtures__/data-v3';
5
+
6
+ const shouldUseNativeValidation = false;
7
+
8
+ describe('zodResolver', () => {
9
+ it('should return values from zodResolver when validation pass & raw=true', async () => {
10
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
11
+
12
+ const result = await zodResolver(schema, undefined, {
13
+ raw: true,
14
+ })(validData, undefined, {
15
+ fields,
16
+ shouldUseNativeValidation,
17
+ });
18
+
19
+ expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
20
+ expect(result).toEqual({ errors: {}, values: validData });
21
+ });
22
+
23
+ it('should return parsed values from zodResolver with `mode: sync` when validation pass', async () => {
24
+ const parseSpy = vi.spyOn(schema, 'parse');
25
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
26
+
27
+ const result = await zodResolver(schema, undefined, {
28
+ mode: 'sync',
29
+ })(validData, undefined, { fields, shouldUseNativeValidation });
30
+
31
+ expect(parseSpy).toHaveBeenCalledTimes(1);
32
+ expect(parseAsyncSpy).not.toHaveBeenCalled();
33
+ expect(result.errors).toEqual({});
34
+ expect(result).toMatchSnapshot();
35
+ });
36
+
37
+ it('should return a single error from zodResolver when validation fails', async () => {
38
+ const result = await zodResolver(schema)(invalidData, undefined, {
39
+ fields,
40
+ shouldUseNativeValidation,
41
+ });
42
+
43
+ expect(result).toMatchSnapshot();
44
+ });
45
+
46
+ it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
47
+ const parseSpy = vi.spyOn(schema, 'parse');
48
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
49
+
50
+ const result = await zodResolver(schema, undefined, {
51
+ mode: 'sync',
52
+ })(invalidData, undefined, { fields, shouldUseNativeValidation });
53
+
54
+ expect(parseSpy).toHaveBeenCalledTimes(1);
55
+ expect(parseAsyncSpy).not.toHaveBeenCalled();
56
+ expect(result).toMatchSnapshot();
57
+ });
58
+
59
+ it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
60
+ const result = await zodResolver(schema)(invalidData, undefined, {
61
+ fields,
62
+ criteriaMode: 'all',
63
+ shouldUseNativeValidation,
64
+ });
65
+
66
+ expect(result).toMatchSnapshot();
67
+ });
68
+
69
+ it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
70
+ const result = await zodResolver(schema, undefined, { mode: 'sync' })(
71
+ invalidData,
72
+ undefined,
73
+ {
74
+ fields,
75
+ criteriaMode: 'all',
76
+ shouldUseNativeValidation,
77
+ },
78
+ );
79
+
80
+ expect(result).toMatchSnapshot();
81
+ });
82
+
83
+ it('should throw any error unrelated to Zod', async () => {
84
+ const schemaWithCustomError = schema.refine(() => {
85
+ throw Error('custom error');
86
+ });
87
+ const promise = zodResolver(schemaWithCustomError)(validData, undefined, {
88
+ fields,
89
+ shouldUseNativeValidation,
90
+ });
91
+
92
+ await expect(promise).rejects.toThrow('custom error');
93
+ });
94
+
95
+ it('should enforce parse params type signature', async () => {
96
+ const resolver = zodResolver(schema, {
97
+ async: true,
98
+ path: ['asdf', 1234],
99
+ errorMap(iss, ctx) {
100
+ iss.path;
101
+ iss.code;
102
+ iss.path;
103
+ ctx.data;
104
+ ctx.defaultError;
105
+ return { message: 'asdf' };
106
+ },
107
+ });
108
+
109
+ resolver;
110
+ });
111
+
112
+ /**
113
+ * Type inference tests
114
+ */
115
+ it('should correctly infer the output type from a zod schema', () => {
116
+ const resolver = zodResolver(z.object({ id: z.number() }));
117
+
118
+ expectTypeOf(resolver).toEqualTypeOf<
119
+ Resolver<{ id: number }, unknown, { id: number }>
120
+ >();
121
+ });
122
+
123
+ it('should correctly infer the output type from a zod schema using a transform', () => {
124
+ const resolver = zodResolver(
125
+ z.object({ id: z.number().transform((val) => String(val)) }),
126
+ );
127
+
128
+ expectTypeOf(resolver).toEqualTypeOf<
129
+ Resolver<{ id: number }, unknown, { id: string }>
130
+ >();
131
+ });
132
+
133
+ it('should correctly infer the output type from a zod schema when a different input type is specified', () => {
134
+ const schema = z.object({ id: z.number() }).transform(({ id }) => {
135
+ return { id: String(id) };
136
+ });
137
+
138
+ const resolver = zodResolver<{ id: number }, any, z.output<typeof schema>>(
139
+ schema,
140
+ );
141
+
142
+ expectTypeOf(resolver).toEqualTypeOf<
143
+ Resolver<{ id: number }, any, { id: string }>
144
+ >();
145
+ });
146
+
147
+ it('should correctly infer the output type from a Zod schema for the handleSubmit function in useForm', () => {
148
+ const schema = z.object({ id: z.number() });
149
+
150
+ const form = useForm({
151
+ resolver: zodResolver(schema),
152
+ });
153
+
154
+ expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
155
+
156
+ expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
157
+ SubmitHandler<{
158
+ id: number;
159
+ }>
160
+ >();
161
+ });
162
+
163
+ it('should correctly infer the output type from a Zod schema with a transform for the handleSubmit function in useForm', () => {
164
+ const schema = z.object({ id: z.number().transform((val) => String(val)) });
165
+
166
+ const form = useForm({
167
+ resolver: zodResolver(schema),
168
+ });
169
+
170
+ expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
171
+
172
+ expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
173
+ SubmitHandler<{
174
+ id: string;
175
+ }>
176
+ >();
177
+ });
178
+ });
@@ -0,0 +1,182 @@
1
+ import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
2
+ import { z } from 'zod/v4-mini';
3
+ import { zodResolver } from '..';
4
+ import {
5
+ fields,
6
+ invalidData,
7
+ schema,
8
+ validData,
9
+ } from './__fixtures__/data-v4-mini';
10
+
11
+ const shouldUseNativeValidation = false;
12
+
13
+ describe('zodResolver', () => {
14
+ it('should return values from zodResolver when validation pass & raw=true', async () => {
15
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
16
+
17
+ const result = await zodResolver(schema, undefined, {
18
+ raw: true,
19
+ })(validData, undefined, {
20
+ fields,
21
+ shouldUseNativeValidation,
22
+ });
23
+ result;
24
+
25
+ expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
26
+ expect(result).toEqual({ errors: {}, values: validData });
27
+ expectTypeOf(result.values);
28
+ });
29
+
30
+ it('should return parsed values from zodResolver with `mode: sync` when validation pass', async () => {
31
+ const parseSpy = vi.spyOn(schema, 'parse');
32
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
33
+
34
+ const result = await zodResolver(schema, undefined, {
35
+ mode: 'sync',
36
+ })(validData, undefined, { fields, shouldUseNativeValidation });
37
+ expect(parseSpy).toHaveBeenCalledTimes(1);
38
+ expect(parseAsyncSpy).not.toHaveBeenCalled();
39
+ expect(result.errors).toEqual({});
40
+ expect(result).toMatchSnapshot();
41
+ });
42
+
43
+ it('should return a single error from zodResolver when validation fails', async () => {
44
+ const result = await zodResolver(schema)(invalidData, undefined, {
45
+ fields,
46
+ shouldUseNativeValidation,
47
+ });
48
+
49
+ expect(result).toMatchSnapshot();
50
+ });
51
+
52
+ it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
53
+ const parseSpy = vi.spyOn(schema, 'parse');
54
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
55
+
56
+ const result = await zodResolver(schema, undefined, {
57
+ mode: 'sync',
58
+ })(invalidData, undefined, { fields, shouldUseNativeValidation });
59
+
60
+ expect(parseSpy).toHaveBeenCalledTimes(1);
61
+ expect(parseAsyncSpy).not.toHaveBeenCalled();
62
+ expect(result).toMatchSnapshot();
63
+ });
64
+
65
+ it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
66
+ const result = await zodResolver(schema)(invalidData, undefined, {
67
+ fields,
68
+ criteriaMode: 'all',
69
+ shouldUseNativeValidation,
70
+ });
71
+
72
+ expect(result).toMatchSnapshot();
73
+ });
74
+
75
+ it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
76
+ const result = await zodResolver(schema, undefined, { mode: 'sync' })(
77
+ invalidData,
78
+ undefined,
79
+ {
80
+ fields,
81
+ criteriaMode: 'all',
82
+ shouldUseNativeValidation,
83
+ },
84
+ );
85
+
86
+ expect(result).toMatchSnapshot();
87
+ });
88
+
89
+ it('should throw any error unrelated to Zod', async () => {
90
+ const schemaWithCustomError = schema.check(
91
+ z.refine(() => {
92
+ throw Error('custom error');
93
+ }),
94
+ );
95
+ const promise = zodResolver(schemaWithCustomError)(validData, undefined, {
96
+ fields,
97
+ shouldUseNativeValidation,
98
+ });
99
+
100
+ await expect(promise).rejects.toThrow('custom error');
101
+ });
102
+
103
+ /**
104
+ * Type inference tests
105
+ */
106
+ it('should correctly infer the output type from a zod schema', () => {
107
+ const resolver = zodResolver(z.object({ id: z.number() }));
108
+
109
+ expectTypeOf(resolver).toEqualTypeOf<
110
+ Resolver<{ id: number }, unknown, { id: number }>
111
+ >();
112
+ });
113
+
114
+ it('should correctly infer the output type from a zod schema using a transform', () => {
115
+ const resolver = zodResolver(
116
+ z.object({
117
+ id: z.pipe(
118
+ z.number(),
119
+ z.transform((val) => String(val)),
120
+ ),
121
+ }),
122
+ );
123
+
124
+ expectTypeOf(resolver).toEqualTypeOf<
125
+ Resolver<{ id: number }, unknown, { id: string }>
126
+ >();
127
+ });
128
+
129
+ it('should correctly infer the output type from a zod schema when a different input type is specified', () => {
130
+ const schema = z.pipe(
131
+ z.object({ id: z.number() }),
132
+ z.transform(({ id }) => {
133
+ return { id: String(id) };
134
+ }),
135
+ );
136
+
137
+ const resolver = zodResolver<{ id: number }, any, z.output<typeof schema>>(
138
+ schema,
139
+ );
140
+
141
+ expectTypeOf(resolver).toEqualTypeOf<
142
+ Resolver<{ id: number }, any, { id: string }>
143
+ >();
144
+ });
145
+
146
+ it('should correctly infer the output type from a Zod schema for the handleSubmit function in useForm', () => {
147
+ const schema = z.object({ id: z.number() });
148
+
149
+ const form = useForm({
150
+ resolver: zodResolver(schema),
151
+ });
152
+
153
+ expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
154
+
155
+ expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
156
+ SubmitHandler<{
157
+ id: number;
158
+ }>
159
+ >();
160
+ });
161
+
162
+ it('should correctly infer the output type from a Zod schema with a transform for the handleSubmit function in useForm', () => {
163
+ const schema = z.object({
164
+ id: z.pipe(
165
+ z.number(),
166
+ z.transform((val) => String(val)),
167
+ ),
168
+ });
169
+
170
+ const form = useForm({
171
+ resolver: zodResolver(schema),
172
+ });
173
+
174
+ expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
175
+
176
+ expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
177
+ SubmitHandler<{
178
+ id: string;
179
+ }>
180
+ >();
181
+ });
182
+ });
@@ -1,7 +1,7 @@
1
1
  import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
2
- import { z } from 'zod';
2
+ import { z } from 'zod/v4';
3
3
  import { zodResolver } from '..';
4
- import { fields, invalidData, schema, validData } from './__fixtures__/data';
4
+ import { fields, invalidData, schema, validData } from './__fixtures__/data-v4';
5
5
 
6
6
  const shouldUseNativeValidation = false;
7
7
 
@@ -92,6 +92,21 @@ describe('zodResolver', () => {
92
92
  await expect(promise).rejects.toThrow('custom error');
93
93
  });
94
94
 
95
+ it('should enforce parse params type signature', async () => {
96
+ const resolver = zodResolver(schema, {
97
+ jitless: true,
98
+ reportInput: true,
99
+ error(iss) {
100
+ iss.path;
101
+ iss.code;
102
+ iss.path;
103
+ return { message: 'asdf' };
104
+ },
105
+ });
106
+
107
+ resolver;
108
+ });
109
+
95
110
  /**
96
111
  * Type inference tests
97
112
  */