@hookform/resolvers 2.8.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +420 -0
  3. package/class-validator/dist/class-validator.d.ts +2 -0
  4. package/class-validator/dist/class-validator.js +2 -0
  5. package/class-validator/dist/class-validator.js.map +1 -0
  6. package/class-validator/dist/class-validator.mjs +2 -0
  7. package/class-validator/dist/class-validator.modern.js +2 -0
  8. package/class-validator/dist/class-validator.modern.js.map +1 -0
  9. package/class-validator/dist/class-validator.module.js +2 -0
  10. package/class-validator/dist/class-validator.module.js.map +1 -0
  11. package/class-validator/dist/class-validator.umd.js +2 -0
  12. package/class-validator/dist/class-validator.umd.js.map +1 -0
  13. package/class-validator/dist/index.d.ts +2 -0
  14. package/class-validator/dist/types.d.ts +8 -0
  15. package/class-validator/package.json +19 -0
  16. package/class-validator/src/__tests__/Form-native-validation.tsx +83 -0
  17. package/class-validator/src/__tests__/Form.tsx +55 -0
  18. package/class-validator/src/__tests__/__fixtures__/data.ts +88 -0
  19. package/class-validator/src/__tests__/__snapshots__/class-validator.ts.snap +207 -0
  20. package/class-validator/src/__tests__/class-validator.ts +87 -0
  21. package/class-validator/src/class-validator.ts +62 -0
  22. package/class-validator/src/index.ts +2 -0
  23. package/class-validator/src/types.ts +22 -0
  24. package/computed-types/dist/computed-types.d.ts +2 -0
  25. package/computed-types/dist/computed-types.js +2 -0
  26. package/computed-types/dist/computed-types.js.map +1 -0
  27. package/computed-types/dist/computed-types.mjs +2 -0
  28. package/computed-types/dist/computed-types.modern.js +2 -0
  29. package/computed-types/dist/computed-types.modern.js.map +1 -0
  30. package/computed-types/dist/computed-types.module.js +2 -0
  31. package/computed-types/dist/computed-types.module.js.map +1 -0
  32. package/computed-types/dist/computed-types.umd.js +2 -0
  33. package/computed-types/dist/computed-types.umd.js.map +1 -0
  34. package/computed-types/dist/index.d.ts +2 -0
  35. package/computed-types/dist/types.d.ts +2 -0
  36. package/computed-types/package.json +17 -0
  37. package/computed-types/src/__tests__/Form-native-validation.tsx +85 -0
  38. package/computed-types/src/__tests__/Form.tsx +54 -0
  39. package/computed-types/src/__tests__/__fixtures__/data.ts +72 -0
  40. package/computed-types/src/__tests__/__snapshots__/computed-types.ts.snap +55 -0
  41. package/computed-types/src/__tests__/computed-types.ts +24 -0
  42. package/computed-types/src/computed-types.ts +43 -0
  43. package/computed-types/src/index.ts +2 -0
  44. package/computed-types/src/types.ts +14 -0
  45. package/dist/index.d.ts +2 -0
  46. package/dist/resolvers.js +2 -0
  47. package/dist/resolvers.js.map +1 -0
  48. package/dist/resolvers.mjs +2 -0
  49. package/dist/resolvers.mjs.map +1 -0
  50. package/dist/resolvers.module.js +2 -0
  51. package/dist/resolvers.module.js.map +1 -0
  52. package/dist/resolvers.umd.js +2 -0
  53. package/dist/resolvers.umd.js.map +1 -0
  54. package/dist/toNestError.d.ts +2 -0
  55. package/dist/validateFieldsNatively.d.ts +2 -0
  56. package/io-ts/dist/arrayToPath.d.ts +3 -0
  57. package/io-ts/dist/errorsToRecord.d.ts +5 -0
  58. package/io-ts/dist/index.d.ts +2 -0
  59. package/io-ts/dist/io-ts.d.ts +2 -0
  60. package/io-ts/dist/io-ts.js +2 -0
  61. package/io-ts/dist/io-ts.js.map +1 -0
  62. package/io-ts/dist/io-ts.mjs +2 -0
  63. package/io-ts/dist/io-ts.modern.js +2 -0
  64. package/io-ts/dist/io-ts.modern.js.map +1 -0
  65. package/io-ts/dist/io-ts.module.js +2 -0
  66. package/io-ts/dist/io-ts.module.js.map +1 -0
  67. package/io-ts/dist/io-ts.umd.js +2 -0
  68. package/io-ts/dist/io-ts.umd.js.map +1 -0
  69. package/io-ts/dist/types.d.ts +7 -0
  70. package/io-ts/package.json +19 -0
  71. package/io-ts/src/__tests__/Form-native-validation.tsx +89 -0
  72. package/io-ts/src/__tests__/Form.tsx +65 -0
  73. package/io-ts/src/__tests__/__fixtures__/data.ts +129 -0
  74. package/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap +89 -0
  75. package/io-ts/src/__tests__/io-ts.ts +37 -0
  76. package/io-ts/src/arrayToPath.ts +18 -0
  77. package/io-ts/src/errorsToRecord.ts +131 -0
  78. package/io-ts/src/index.ts +2 -0
  79. package/io-ts/src/io-ts.ts +33 -0
  80. package/io-ts/src/types.ts +23 -0
  81. package/joi/dist/index.d.ts +2 -0
  82. package/joi/dist/joi.d.ts +2 -0
  83. package/joi/dist/joi.js +2 -0
  84. package/joi/dist/joi.js.map +1 -0
  85. package/joi/dist/joi.mjs +2 -0
  86. package/joi/dist/joi.modern.js +2 -0
  87. package/joi/dist/joi.modern.js.map +1 -0
  88. package/joi/dist/joi.module.js +2 -0
  89. package/joi/dist/joi.module.js.map +1 -0
  90. package/joi/dist/joi.umd.js +2 -0
  91. package/joi/dist/joi.umd.js.map +1 -0
  92. package/joi/dist/types.d.ts +5 -0
  93. package/joi/package.json +17 -0
  94. package/joi/src/__tests__/Form-native-validation.tsx +89 -0
  95. package/joi/src/__tests__/Form.tsx +61 -0
  96. package/joi/src/__tests__/__fixtures__/data.ts +85 -0
  97. package/joi/src/__tests__/__snapshots__/joi.ts.snap +293 -0
  98. package/joi/src/__tests__/joi.ts +98 -0
  99. package/joi/src/index.ts +2 -0
  100. package/joi/src/joi.ts +81 -0
  101. package/joi/src/types.ts +16 -0
  102. package/nope/dist/index.d.ts +2 -0
  103. package/nope/dist/nope.d.ts +2 -0
  104. package/nope/dist/nope.js +2 -0
  105. package/nope/dist/nope.js.map +1 -0
  106. package/nope/dist/nope.mjs +2 -0
  107. package/nope/dist/nope.modern.js +2 -0
  108. package/nope/dist/nope.modern.js.map +1 -0
  109. package/nope/dist/nope.module.js +2 -0
  110. package/nope/dist/nope.module.js.map +1 -0
  111. package/nope/dist/nope.umd.js +2 -0
  112. package/nope/dist/nope.umd.js.map +1 -0
  113. package/nope/dist/types.d.ts +6 -0
  114. package/nope/package.json +18 -0
  115. package/nope/src/__tests__/Form-native-validation.tsx +89 -0
  116. package/nope/src/__tests__/Form.tsx +57 -0
  117. package/nope/src/__tests__/__fixtures__/data.ts +70 -0
  118. package/nope/src/__tests__/__snapshots__/nope.ts.snap +43 -0
  119. package/nope/src/__tests__/nope.ts +28 -0
  120. package/nope/src/index.ts +2 -0
  121. package/nope/src/nope.ts +46 -0
  122. package/nope/src/types.ts +22 -0
  123. package/package.json +216 -0
  124. package/superstruct/dist/index.d.ts +2 -0
  125. package/superstruct/dist/superstruct.d.ts +2 -0
  126. package/superstruct/dist/superstruct.js +2 -0
  127. package/superstruct/dist/superstruct.js.map +1 -0
  128. package/superstruct/dist/superstruct.mjs +2 -0
  129. package/superstruct/dist/superstruct.modern.js +2 -0
  130. package/superstruct/dist/superstruct.modern.js.map +1 -0
  131. package/superstruct/dist/superstruct.module.js +2 -0
  132. package/superstruct/dist/superstruct.module.js.map +1 -0
  133. package/superstruct/dist/superstruct.umd.js +2 -0
  134. package/superstruct/dist/superstruct.umd.js.map +1 -0
  135. package/superstruct/dist/types.d.ts +5 -0
  136. package/superstruct/package.json +18 -0
  137. package/superstruct/src/__tests__/Form-native-validation.tsx +86 -0
  138. package/superstruct/src/__tests__/Form.tsx +62 -0
  139. package/superstruct/src/__tests__/__fixtures__/data.ts +75 -0
  140. package/superstruct/src/__tests__/__snapshots__/superstruct.ts.snap +64 -0
  141. package/superstruct/src/__tests__/superstruct.ts +24 -0
  142. package/superstruct/src/index.ts +2 -0
  143. package/superstruct/src/superstruct.ts +37 -0
  144. package/superstruct/src/types.ts +17 -0
  145. package/typanion/dist/index.d.ts +2 -0
  146. package/typanion/dist/typanion.d.ts +2 -0
  147. package/typanion/dist/typanion.js +2 -0
  148. package/typanion/dist/typanion.js.map +1 -0
  149. package/typanion/dist/typanion.mjs +2 -0
  150. package/typanion/dist/typanion.modern.js +2 -0
  151. package/typanion/dist/typanion.modern.js.map +1 -0
  152. package/typanion/dist/typanion.module.js +2 -0
  153. package/typanion/dist/typanion.module.js.map +1 -0
  154. package/typanion/dist/typanion.umd.js +2 -0
  155. package/typanion/dist/typanion.umd.js.map +1 -0
  156. package/typanion/dist/types.d.ts +6 -0
  157. package/typanion/package.json +18 -0
  158. package/typanion/src/__tests__/Form-native-validation.tsx +89 -0
  159. package/typanion/src/__tests__/Form.tsx +61 -0
  160. package/typanion/src/__tests__/__fixtures__/data.ts +77 -0
  161. package/typanion/src/__tests__/__snapshots__/typanion.ts.snap +67 -0
  162. package/typanion/src/__tests__/typanion.ts +31 -0
  163. package/typanion/src/index.ts +2 -0
  164. package/typanion/src/typanion.ts +44 -0
  165. package/typanion/src/types.ts +28 -0
  166. package/vest/dist/index.d.ts +1 -0
  167. package/vest/dist/vest.d.ts +2 -0
  168. package/vest/dist/vest.js +2 -0
  169. package/vest/dist/vest.js.map +1 -0
  170. package/vest/dist/vest.mjs +2 -0
  171. package/vest/dist/vest.modern.js +2 -0
  172. package/vest/dist/vest.modern.js.map +1 -0
  173. package/vest/dist/vest.module.js +2 -0
  174. package/vest/dist/vest.module.js.map +1 -0
  175. package/vest/dist/vest.umd.js +2 -0
  176. package/vest/dist/vest.umd.js.map +1 -0
  177. package/vest/package.json +18 -0
  178. package/vest/src/__tests__/Form-native-validation.tsx +93 -0
  179. package/vest/src/__tests__/Form.tsx +64 -0
  180. package/vest/src/__tests__/__fixtures__/data.ts +67 -0
  181. package/vest/src/__tests__/__snapshots__/vest.ts.snap +141 -0
  182. package/vest/src/__tests__/vest.ts +71 -0
  183. package/vest/src/index.ts +1 -0
  184. package/vest/src/types.ts +20 -0
  185. package/vest/src/vest.ts +51 -0
  186. package/yup/dist/index.d.ts +2 -0
  187. package/yup/dist/types.d.ts +8 -0
  188. package/yup/dist/yup.d.ts +2 -0
  189. package/yup/dist/yup.js +2 -0
  190. package/yup/dist/yup.js.map +1 -0
  191. package/yup/dist/yup.mjs +2 -0
  192. package/yup/dist/yup.modern.js +2 -0
  193. package/yup/dist/yup.modern.js.map +1 -0
  194. package/yup/dist/yup.module.js +2 -0
  195. package/yup/dist/yup.module.js.map +1 -0
  196. package/yup/dist/yup.umd.js +2 -0
  197. package/yup/dist/yup.umd.js.map +1 -0
  198. package/yup/package.json +17 -0
  199. package/yup/src/__tests__/Form-native-validation.tsx +85 -0
  200. package/yup/src/__tests__/Form.tsx +54 -0
  201. package/yup/src/__tests__/__fixtures__/data.ts +72 -0
  202. package/yup/src/__tests__/__snapshots__/yup.ts.snap +231 -0
  203. package/yup/src/__tests__/yup.ts +174 -0
  204. package/yup/src/index.ts +2 -0
  205. package/yup/src/types.ts +21 -0
  206. package/yup/src/yup.ts +75 -0
  207. package/zod/dist/index.d.ts +2 -0
  208. package/zod/dist/types.d.ts +5 -0
  209. package/zod/dist/zod.d.ts +2 -0
  210. package/zod/dist/zod.js +2 -0
  211. package/zod/dist/zod.js.map +1 -0
  212. package/zod/dist/zod.mjs +2 -0
  213. package/zod/dist/zod.modern.js +2 -0
  214. package/zod/dist/zod.modern.js.map +1 -0
  215. package/zod/dist/zod.module.js +2 -0
  216. package/zod/dist/zod.module.js.map +1 -0
  217. package/zod/dist/zod.umd.js +2 -0
  218. package/zod/dist/zod.umd.js.map +1 -0
  219. package/zod/package.json +17 -0
  220. package/zod/src/__tests__/Form-native-validation.tsx +85 -0
  221. package/zod/src/__tests__/Form.tsx +54 -0
  222. package/zod/src/__tests__/__fixtures__/data.ts +81 -0
  223. package/zod/src/__tests__/__snapshots__/zod.ts.snap +377 -0
  224. package/zod/src/__tests__/zod.ts +77 -0
  225. package/zod/src/index.ts +2 -0
  226. package/zod/src/types.ts +16 -0
  227. package/zod/src/zod.ts +85 -0
package/yup/src/yup.ts ADDED
@@ -0,0 +1,75 @@
1
+ import Yup, { ValidationError } from 'yup';
2
+ import { toNestError, validateFieldsNatively } from '@hookform/resolvers';
3
+ import { appendErrors, FieldError } from 'react-hook-form';
4
+ import { Resolver } from './types';
5
+
6
+ /**
7
+ * Why `path!` ? because it could be `undefined` in some case
8
+ * https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
9
+ */
10
+ const parseErrorSchema = (
11
+ error: Yup.ValidationError,
12
+ validateAllFieldCriteria: boolean,
13
+ ) => {
14
+ return error.inner.reduce<Record<string, FieldError>>((previous, error) => {
15
+ if (!previous[error.path!]) {
16
+ previous[error.path!] = { message: error.message, type: error.type! };
17
+ }
18
+
19
+ if (validateAllFieldCriteria) {
20
+ const types = previous[error.path!].types;
21
+ const messages = types && types[error.type!];
22
+
23
+ previous[error.path!] = appendErrors(
24
+ error.path!,
25
+ validateAllFieldCriteria,
26
+ previous,
27
+ error.type!,
28
+ messages
29
+ ? ([] as string[]).concat(messages as string[], error.message)
30
+ : error.message,
31
+ ) as FieldError;
32
+ }
33
+
34
+ return previous;
35
+ }, {});
36
+ };
37
+
38
+ export const yupResolver: Resolver =
39
+ (schema, schemaOptions = {}, resolverOptions = {}) =>
40
+ async (values, context, options) => {
41
+ try {
42
+ if (schemaOptions.context && process.env.NODE_ENV === 'development') {
43
+ // eslint-disable-next-line no-console
44
+ console.warn(
45
+ "You should not used the yup options context. Please, use the 'useForm' context object instead",
46
+ );
47
+ }
48
+
49
+ const result = await schema[
50
+ resolverOptions.mode === 'sync' ? 'validateSync' : 'validate'
51
+ ](
52
+ values,
53
+ Object.assign({ abortEarly: false }, schemaOptions, { context }),
54
+ );
55
+
56
+ options.shouldUseNativeValidation && validateFieldsNatively({}, options);
57
+
58
+ return {
59
+ values: result,
60
+ errors: {},
61
+ };
62
+ } catch (e) {
63
+ return {
64
+ values: {},
65
+ errors: toNestError(
66
+ parseErrorSchema(
67
+ e as ValidationError,
68
+ !options.shouldUseNativeValidation &&
69
+ options.criteriaMode === 'all',
70
+ ),
71
+ options,
72
+ ),
73
+ };
74
+ }
75
+ };
@@ -0,0 +1,2 @@
1
+ export * from './zod';
2
+ export * from './types';
@@ -0,0 +1,5 @@
1
+ import { ResolverResult, ResolverOptions, FieldValues } from 'react-hook-form';
2
+ import { z } from 'zod';
3
+ export declare type Resolver = <TFieldValues extends FieldValues, TContext extends object = object>(schema: z.Schema<TFieldValues, any>, schemaOptions?: Partial<z.ParseParamsNoData>, factoryOptions?: {
4
+ mode?: 'async' | 'sync';
5
+ }) => (values: unknown, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
@@ -0,0 +1,2 @@
1
+ import type { Resolver } from './types';
2
+ export declare const zodResolver: Resolver;
@@ -0,0 +1,2 @@
1
+ var r=require("react-hook-form"),e=require("@hookform/resolvers"),o=function(e,o){for(var s={};e.length;){var n=e[0],t=n.code,i=n.message,a=n.path.join(".");if(!s[a])if("unionErrors"in n){var u=n.unionErrors[0].errors[0];s[a]={message:u.message,type:u.code}}else s[a]={message:i,type:t};if("unionErrors"in n&&n.unionErrors.forEach(function(r){return r.errors.forEach(function(r){return e.push(r)})}),o){var c=s[a].types,v=c&&c[n.code];s[a]=r.appendErrors(a,o,s,t,v?[].concat(v,n.message):n.message)}e.shift()}return s};exports.zodResolver=function(r,s,n){return void 0===n&&(n={}),function(t,i,a){try{return Promise.resolve(function(o,i){try{var u=Promise.resolve(r["sync"===n.mode?"parse":"parseAsync"](t,s)).then(function(r){return a.shouldUseNativeValidation&&e.validateFieldsNatively({},a),{errors:{},values:r}})}catch(r){return i(r)}return u&&u.then?u.then(void 0,i):u}(0,function(r){return{values:{},errors:r.isEmpty?{}:e.toNestError(o(r.errors,!a.shouldUseNativeValidation&&"all"===a.criteriaMode),a)}}))}catch(r){return Promise.reject(r)}}};
2
+ //# sourceMappingURL=zod.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.js","sources":["../src/zod.ts"],"sourcesContent":["import { appendErrors, FieldError, FieldErrors } from 'react-hook-form';\nimport { z, ZodError } from 'zod';\nimport { toNestError, validateFieldsNatively } from '@hookform/resolvers';\nimport type { Resolver } from './types';\n\nconst 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 const zodResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, 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<any>,\n values: data,\n };\n } catch (error) {\n return {\n values: {},\n errors: (error as ZodError).isEmpty\n ? ({} as FieldErrors<any>)\n : (toNestError(\n parseErrorSchema(\n (error as ZodError).errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ) as FieldErrors<any>),\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","mode","data","shouldUseNativeValidation","validateFieldsNatively","isEmpty","toNestError","criteriaMode"],"mappings":"kEAKMA,EAAmB,SACvBC,EACAC,GAGA,IADA,IAAMC,EAAqC,GACpCF,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,WAGnBH,EAAOK,GAAS,CAAED,QAAAA,EAASM,KAAMP,GAUrC,GANI,gBAAiBD,GACnBA,EAAMO,YAAYE,QAAQ,SAACH,UACzBA,EAAWR,OAAOW,QAAQ,SAACC,UAAMd,EAAUe,KAAKD,OAIhDb,EAA0B,CAC5B,IAAMe,EAAQd,EAAOK,GAAOS,MACtBC,EAAWD,GAASA,EAAMZ,EAAMC,MAEtCH,EAAOK,GAASW,eACdX,EACAN,EACAC,EACAG,EACAY,EACK,GAAgBE,OAAOF,EAAsBb,EAAME,SACpDF,EAAME,SAIdN,EAAUoB,QAGZ,OAAOlB,uBAIP,SAACmB,EAAQC,EAAeC,mBAAAA,IAAAA,EAAkB,aACnCC,EAAQC,EAAGC,sEAEKL,EACQ,SAAzBE,EAAgBI,KAAkB,QAAU,cAC5CH,EAAQF,kBAFJM,GAMN,OAFAF,EAAQG,2BAA6BC,yBAAuB,GAAIJ,GAEzD,CACLxB,OAAQ,GACRsB,OAAQI,0EAEHxB,GACP,MAAO,CACLoB,OAAQ,GACRtB,OAASE,EAAmB2B,QACvB,GACAC,cACCjC,EACGK,EAAmBF,QACnBwB,EAAQG,2BACkB,QAAzBH,EAAQO,cAEZP,OAxBZ"}
@@ -0,0 +1,2 @@
1
+ import{appendErrors as r}from"react-hook-form";import{validateFieldsNatively as e,toNestError as o}from"@hookform/resolvers";var n=function(e,o){for(var n={};e.length;){var s=e[0],t=s.code,i=s.message,a=s.path.join(".");if(!n[a])if("unionErrors"in s){var u=s.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:t};if("unionErrors"in s&&s.unionErrors.forEach(function(r){return r.errors.forEach(function(r){return e.push(r)})}),o){var c=n[a].types,f=c&&c[s.code];n[a]=r(a,o,n,t,f?[].concat(f,s.message):s.message)}e.shift()}return n},s=function(r,s,t){return void 0===t&&(t={}),function(i,a,u){try{return Promise.resolve(function(o,n){try{var a=Promise.resolve(r["sync"===t.mode?"parse":"parseAsync"](i,s)).then(function(r){return u.shouldUseNativeValidation&&e({},u),{errors:{},values:r}})}catch(r){return n(r)}return a&&a.then?a.then(void 0,n):a}(0,function(r){return{values:{},errors:r.isEmpty?{}:o(n(r.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}}))}catch(r){return Promise.reject(r)}}};export{s as zodResolver};
2
+ //# sourceMappingURL=zod.module.js.map
@@ -0,0 +1,2 @@
1
+ import{appendErrors as r}from"react-hook-form";import{validateFieldsNatively as o,toNestError as s}from"@hookform/resolvers";const e=(o,s)=>{const e={};for(;o.length;){const t=o[0],{code:a,message:n,path:i}=t,c=i.join(".");if(!e[c])if("unionErrors"in t){const r=t.unionErrors[0].errors[0];e[c]={message:r.message,type:r.code}}else e[c]={message:n,type:a};if("unionErrors"in t&&t.unionErrors.forEach(r=>r.errors.forEach(r=>o.push(r))),s){const o=e[c].types,n=o&&o[t.code];e[c]=r(c,s,e,a,n?[].concat(n,t.message):t.message)}o.shift()}return e},t=(r,t,a={})=>async(n,i,c)=>{try{const s=await r["sync"===a.mode?"parse":"parseAsync"](n,t);return c.shouldUseNativeValidation&&o({},c),{errors:{},values:s}}catch(r){return{values:{},errors:r.isEmpty?{}:s(e(r.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}}};export{t as zodResolver};
2
+ //# sourceMappingURL=zod.modern.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.modern.js","sources":["../src/zod.ts"],"sourcesContent":["import { appendErrors, FieldError, FieldErrors } from 'react-hook-form';\nimport { z, ZodError } from 'zod';\nimport { toNestError, validateFieldsNatively } from '@hookform/resolvers';\nimport type { Resolver } from './types';\n\nconst 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 const zodResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, 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<any>,\n values: data,\n };\n } catch (error) {\n return {\n values: {},\n errors: (error as ZodError).isEmpty\n ? ({} as FieldErrors<any>)\n : (toNestError(\n parseErrorSchema(\n (error as ZodError).errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ) as FieldErrors<any>),\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","zodResolver","schema","schemaOptions","resolverOptions","async","values","_","options","data","mode","shouldUseNativeValidation","validateFieldsNatively","isEmpty","toNestError","criteriaMode"],"mappings":"6HAKA,MAAMA,EAAmB,CACvBC,EACAC,KAEA,MAAMC,EAAqC,GAC3C,KAAOF,EAAUG,QAAU,CACzB,MAAMC,EAAQJ,EAAU,IAClBK,KAAEA,EAAFC,QAAQA,EAARC,KAAiBA,GAASH,EAC1BI,EAAQD,EAAKE,KAAK,KAExB,IAAKP,EAAOM,GACV,GAAI,gBAAiBJ,EAAO,CAC1B,MAAMM,EAAaN,EAAMO,YAAY,GAAGT,OAAO,GAE/CA,EAAOM,GAAS,CACdF,QAASI,EAAWJ,QACpBM,KAAMF,EAAWL,WAGnBH,EAAOM,GAAS,CAAEF,QAAAA,EAASM,KAAMP,GAUrC,GANI,gBAAiBD,GACnBA,EAAMO,YAAYE,QAASH,GACzBA,EAAWR,OAAOW,QAASC,GAAMd,EAAUe,KAAKD,KAIhDb,EAA0B,CAC5B,MAAMe,EAAQd,EAAOM,GAAOQ,MACtBC,EAAWD,GAASA,EAAMZ,EAAMC,MAEtCH,EAAOM,GAASU,EACdV,EACAP,EACAC,EACAG,EACAY,EACK,GAAgBE,OAAOF,EAAsBb,EAAME,SACpDF,EAAME,SAIdN,EAAUoB,QAGZ,OAAOlB,GAGImB,EACX,CAACC,EAAQC,EAAeC,EAAkB,KAC1CC,MAAOC,EAAQC,EAAGC,KAChB,IACE,MAAMC,QAAaP,EACQ,SAAzBE,EAAgBM,KAAkB,QAAU,cAC5CJ,EAAQH,GAIV,OAFAK,EAAQG,2BAA6BC,EAAuB,GAAIJ,GAEzD,CACL1B,OAAQ,GACRwB,OAAQG,GAEV,MAAOzB,GACP,MAAO,CACLsB,OAAQ,GACRxB,OAASE,EAAmB6B,QACvB,GACAC,EACCnC,EACGK,EAAmBF,QACnB0B,EAAQG,2BACkB,QAAzBH,EAAQO,cAEZP"}
@@ -0,0 +1,2 @@
1
+ import{appendErrors as r}from"react-hook-form";import{validateFieldsNatively as e,toNestError as o}from"@hookform/resolvers";var n=function(e,o){for(var n={};e.length;){var s=e[0],t=s.code,i=s.message,a=s.path.join(".");if(!n[a])if("unionErrors"in s){var u=s.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:t};if("unionErrors"in s&&s.unionErrors.forEach(function(r){return r.errors.forEach(function(r){return e.push(r)})}),o){var c=n[a].types,f=c&&c[s.code];n[a]=r(a,o,n,t,f?[].concat(f,s.message):s.message)}e.shift()}return n},s=function(r,s,t){return void 0===t&&(t={}),function(i,a,u){try{return Promise.resolve(function(o,n){try{var a=Promise.resolve(r["sync"===t.mode?"parse":"parseAsync"](i,s)).then(function(r){return u.shouldUseNativeValidation&&e({},u),{errors:{},values:r}})}catch(r){return n(r)}return a&&a.then?a.then(void 0,n):a}(0,function(r){return{values:{},errors:r.isEmpty?{}:o(n(r.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}}))}catch(r){return Promise.reject(r)}}};export{s as zodResolver};
2
+ //# sourceMappingURL=zod.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.module.js","sources":["../src/zod.ts"],"sourcesContent":["import { appendErrors, FieldError, FieldErrors } from 'react-hook-form';\nimport { z, ZodError } from 'zod';\nimport { toNestError, validateFieldsNatively } from '@hookform/resolvers';\nimport type { Resolver } from './types';\n\nconst 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 const zodResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, 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<any>,\n values: data,\n };\n } catch (error) {\n return {\n values: {},\n errors: (error as ZodError).isEmpty\n ? ({} as FieldErrors<any>)\n : (toNestError(\n parseErrorSchema(\n (error as ZodError).errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ) as FieldErrors<any>),\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","zodResolver","schema","schemaOptions","resolverOptions","values","_","options","mode","data","shouldUseNativeValidation","validateFieldsNatively","isEmpty","toNestError","criteriaMode"],"mappings":"6HAKA,IAAMA,EAAmB,SACvBC,EACAC,GAGA,IADA,IAAMC,EAAqC,GACpCF,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,WAGnBH,EAAOK,GAAS,CAAED,QAAAA,EAASM,KAAMP,GAUrC,GANI,gBAAiBD,GACnBA,EAAMO,YAAYE,QAAQ,SAACH,UACzBA,EAAWR,OAAOW,QAAQ,SAACC,UAAMd,EAAUe,KAAKD,OAIhDb,EAA0B,CAC5B,IAAMe,EAAQd,EAAOK,GAAOS,MACtBC,EAAWD,GAASA,EAAMZ,EAAMC,MAEtCH,EAAOK,GAASW,EACdX,EACAN,EACAC,EACAG,EACAY,EACK,GAAgBE,OAAOF,EAAsBb,EAAME,SACpDF,EAAME,SAIdN,EAAUoB,QAGZ,OAAOlB,GAGImB,EACX,SAACC,EAAQC,EAAeC,mBAAAA,IAAAA,EAAkB,aACnCC,EAAQC,EAAGC,sEAEKL,EACQ,SAAzBE,EAAgBI,KAAkB,QAAU,cAC5CH,EAAQF,kBAFJM,GAMN,OAFAF,EAAQG,2BAA6BC,EAAuB,GAAIJ,GAEzD,CACLzB,OAAQ,GACRuB,OAAQI,0EAEHzB,GACP,MAAO,CACLqB,OAAQ,GACRvB,OAASE,EAAmB4B,QACvB,GACAC,EACClC,EACGK,EAAmBF,QACnByB,EAAQG,2BACkB,QAAzBH,EAAQO,cAEZP,OAxBZ"}
@@ -0,0 +1,2 @@
1
+ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react-hook-form"),require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","react-hook-form","@hookform/resolvers"],r):r((e||self).hookformResolversZod={},e.reactHookForm,e.hookformResolvers)}(this,function(e,r,o){var n=function(e,o){for(var n={};e.length;){var s=e[0],t=s.code,i=s.message,a=s.path.join(".");if(!n[a])if("unionErrors"in s){var u=s.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:t};if("unionErrors"in s&&s.unionErrors.forEach(function(r){return r.errors.forEach(function(r){return e.push(r)})}),o){var f=n[a].types,c=f&&f[s.code];n[a]=r.appendErrors(a,o,n,t,c?[].concat(c,s.message):s.message)}e.shift()}return n};e.zodResolver=function(e,r,s){return void 0===s&&(s={}),function(t,i,a){try{return Promise.resolve(function(n,i){try{var u=Promise.resolve(e["sync"===s.mode?"parse":"parseAsync"](t,r)).then(function(e){return a.shouldUseNativeValidation&&o.validateFieldsNatively({},a),{errors:{},values:e}})}catch(e){return i(e)}return u&&u.then?u.then(void 0,i):u}(0,function(e){return{values:{},errors:e.isEmpty?{}:o.toNestError(n(e.errors,!a.shouldUseNativeValidation&&"all"===a.criteriaMode),a)}}))}catch(e){return Promise.reject(e)}}}});
2
+ //# sourceMappingURL=zod.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.umd.js","sources":["../src/zod.ts"],"sourcesContent":["import { appendErrors, FieldError, FieldErrors } from 'react-hook-form';\nimport { z, ZodError } from 'zod';\nimport { toNestError, validateFieldsNatively } from '@hookform/resolvers';\nimport type { Resolver } from './types';\n\nconst 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 const zodResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, 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<any>,\n values: data,\n };\n } catch (error) {\n return {\n values: {},\n errors: (error as ZodError).isEmpty\n ? ({} as FieldErrors<any>)\n : (toNestError(\n parseErrorSchema(\n (error as ZodError).errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ) as FieldErrors<any>),\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","mode","data","shouldUseNativeValidation","validateFieldsNatively","isEmpty","toNestError","criteriaMode"],"mappings":"wXAKA,IAAMA,EAAmB,SACvBC,EACAC,GAGA,IADA,IAAMC,EAAqC,GACpCF,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,WAGnBH,EAAOK,GAAS,CAAED,QAAAA,EAASM,KAAMP,GAUrC,GANI,gBAAiBD,GACnBA,EAAMO,YAAYE,QAAQ,SAACH,UACzBA,EAAWR,OAAOW,QAAQ,SAACC,UAAMd,EAAUe,KAAKD,OAIhDb,EAA0B,CAC5B,IAAMe,EAAQd,EAAOK,GAAOS,MACtBC,EAAWD,GAASA,EAAMZ,EAAMC,MAEtCH,EAAOK,GAASW,eACdX,EACAN,EACAC,EACAG,EACAY,EACK,GAAgBE,OAAOF,EAAsBb,EAAME,SACpDF,EAAME,SAIdN,EAAUoB,QAGZ,OAAOlB,iBAIP,SAACmB,EAAQC,EAAeC,mBAAAA,IAAAA,EAAkB,aACnCC,EAAQC,EAAGC,sEAEKL,EACQ,SAAzBE,EAAgBI,KAAkB,QAAU,cAC5CH,EAAQF,kBAFJM,GAMN,OAFAF,EAAQG,2BAA6BC,yBAAuB,GAAIJ,GAEzD,CACLxB,OAAQ,GACRsB,OAAQI,0EAEHxB,GACP,MAAO,CACLoB,OAAQ,GACRtB,OAASE,EAAmB2B,QACvB,GACAC,cACCjC,EACGK,EAAmBF,QACnBwB,EAAQG,2BACkB,QAAzBH,EAAQO,cAEZP,OAxBZ"}
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "zod",
3
+ "amdName": "hookformResolversZod",
4
+ "version": "1.0.0",
5
+ "private": true,
6
+ "description": "React Hook Form validation resolver: zod",
7
+ "main": "dist/zod.js",
8
+ "module": "dist/zod.module.js",
9
+ "umd:main": "dist/zod.umd.js",
10
+ "source": "src/index.ts",
11
+ "types": "dist/index.d.ts",
12
+ "license": "MIT",
13
+ "peerDependencies": {
14
+ "react-hook-form": "^7.0.0",
15
+ "@hookform/resolvers": "^2.0.0"
16
+ }
17
+ }
@@ -0,0 +1,85 @@
1
+ import React from 'react';
2
+ import { useForm } from 'react-hook-form';
3
+ import { act, render, screen } from '@testing-library/react';
4
+ import user from '@testing-library/user-event';
5
+ import { z } from 'zod';
6
+ import { zodResolver } from '..';
7
+
8
+ const USERNAME_REQUIRED_MESSAGE = 'username field is required';
9
+ const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
10
+
11
+ const schema = z.object({
12
+ username: z.string().nonempty({ message: USERNAME_REQUIRED_MESSAGE }),
13
+ password: z.string().nonempty({ message: PASSWORD_REQUIRED_MESSAGE }),
14
+ });
15
+
16
+ type FormData = z.infer<typeof schema>;
17
+
18
+ interface Props {
19
+ onSubmit: (data: FormData) => void;
20
+ }
21
+
22
+ function TestComponent({ onSubmit }: Props) {
23
+ const { register, handleSubmit } = useForm<FormData>({
24
+ resolver: zodResolver(schema),
25
+ shouldUseNativeValidation: true,
26
+ });
27
+
28
+ return (
29
+ <form onSubmit={handleSubmit(onSubmit)}>
30
+ <input {...register('username')} placeholder="username" />
31
+
32
+ <input {...register('password')} placeholder="password" />
33
+
34
+ <button type="submit">submit</button>
35
+ </form>
36
+ );
37
+ }
38
+
39
+ test("form's native validation with Zod", async () => {
40
+ const handleSubmit = jest.fn();
41
+ render(<TestComponent onSubmit={handleSubmit} />);
42
+
43
+ // username
44
+ let usernameField = screen.getByPlaceholderText(
45
+ /username/i,
46
+ ) as HTMLInputElement;
47
+ expect(usernameField.validity.valid).toBe(true);
48
+ expect(usernameField.validationMessage).toBe('');
49
+
50
+ // password
51
+ let passwordField = screen.getByPlaceholderText(
52
+ /password/i,
53
+ ) as HTMLInputElement;
54
+ expect(passwordField.validity.valid).toBe(true);
55
+ expect(passwordField.validationMessage).toBe('');
56
+
57
+ await act(async () => {
58
+ user.click(screen.getByText(/submit/i));
59
+ });
60
+
61
+ // username
62
+ usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
63
+ expect(usernameField.validity.valid).toBe(false);
64
+ expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);
65
+
66
+ // password
67
+ passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
68
+ expect(passwordField.validity.valid).toBe(false);
69
+ expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
70
+
71
+ await act(async () => {
72
+ user.type(screen.getByPlaceholderText(/username/i), 'joe');
73
+ user.type(screen.getByPlaceholderText(/password/i), 'password');
74
+ });
75
+
76
+ // username
77
+ usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
78
+ expect(usernameField.validity.valid).toBe(true);
79
+ expect(usernameField.validationMessage).toBe('');
80
+
81
+ // password
82
+ passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
83
+ expect(passwordField.validity.valid).toBe(true);
84
+ expect(passwordField.validationMessage).toBe('');
85
+ });
@@ -0,0 +1,54 @@
1
+ import React from 'react';
2
+ import { render, screen, act } from '@testing-library/react';
3
+ import user from '@testing-library/user-event';
4
+ import { useForm } from 'react-hook-form';
5
+ import { z } from 'zod';
6
+ import { zodResolver } from '..';
7
+
8
+ const schema = z.object({
9
+ username: z.string().nonempty({ message: 'username field is required' }),
10
+ password: z.string().nonempty({ message: 'password field is required' }),
11
+ });
12
+
13
+ type FormData = z.infer<typeof schema> & { unusedProperty: string };
14
+
15
+ interface Props {
16
+ onSubmit: (data: FormData) => void;
17
+ }
18
+
19
+ function TestComponent({ onSubmit }: Props) {
20
+ const {
21
+ register,
22
+ handleSubmit,
23
+ formState: { errors },
24
+ } = useForm({
25
+ resolver: zodResolver(schema), // Useful to check TypeScript regressions
26
+ });
27
+
28
+ return (
29
+ <form onSubmit={handleSubmit(onSubmit)}>
30
+ <input {...register('username')} />
31
+ {errors.username && <span role="alert">{errors.username.message}</span>}
32
+
33
+ <input {...register('password')} />
34
+ {errors.password && <span role="alert">{errors.password.message}</span>}
35
+
36
+ <button type="submit">submit</button>
37
+ </form>
38
+ );
39
+ }
40
+
41
+ test("form's validation with Zod and TypeScript's integration", async () => {
42
+ const handleSubmit = jest.fn();
43
+ render(<TestComponent onSubmit={handleSubmit} />);
44
+
45
+ expect(screen.queryAllByRole(/alert/i)).toHaveLength(0);
46
+
47
+ await act(async () => {
48
+ user.click(screen.getByText(/submit/i));
49
+ });
50
+
51
+ expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
52
+ expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
53
+ expect(handleSubmit).not.toHaveBeenCalled();
54
+ });
@@ -0,0 +1,81 @@
1
+ import { Field, InternalFieldName } from 'react-hook-form';
2
+ import { z } from 'zod';
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
+ enabled: z.boolean(),
23
+ url: z.string().url('Custom error url').or(z.literal('')),
24
+ like: z
25
+ .array(
26
+ z.object({
27
+ id: z.number(),
28
+ name: z.string().length(4),
29
+ }),
30
+ )
31
+ .optional(),
32
+ })
33
+ .refine((obj) => obj.password === obj.repeatPassword, {
34
+ message: 'Passwords do not match',
35
+ path: ['confirm'],
36
+ });
37
+
38
+ export const validData: z.infer<typeof schema> = {
39
+ username: 'Doe',
40
+ password: 'Password123_',
41
+ repeatPassword: 'Password123_',
42
+ birthYear: 2000,
43
+ email: 'john@doe.com',
44
+ tags: ['tag1', 'tag2'],
45
+ enabled: true,
46
+ accessToken: 'accessToken',
47
+ url: 'https://react-hook-form.com/',
48
+ like: [
49
+ {
50
+ id: 1,
51
+ name: 'name',
52
+ },
53
+ ],
54
+ };
55
+
56
+ export const invalidData = {
57
+ password: '___',
58
+ email: '',
59
+ birthYear: 'birthYear',
60
+ like: [{ id: 'z' }],
61
+ url: 'abc',
62
+ };
63
+
64
+ export const fields: Record<InternalFieldName, Field['_f']> = {
65
+ username: {
66
+ ref: { name: 'username' },
67
+ name: 'username',
68
+ },
69
+ password: {
70
+ ref: { name: 'password' },
71
+ name: 'password',
72
+ },
73
+ email: {
74
+ ref: { name: 'email' },
75
+ name: 'email',
76
+ },
77
+ birthday: {
78
+ ref: { name: 'birthday' },
79
+ name: 'birthday',
80
+ },
81
+ };