remix-validated-form 2.0.0 → 2.0.1-beta.0

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 (101) hide show
  1. package/.turbo/turbo-build.log +9 -0
  2. package/.turbo/turbo-dev.log +0 -0
  3. package/browser/ValidatedForm.d.ts +0 -0
  4. package/browser/ValidatedForm.js +0 -0
  5. package/browser/hooks.d.ts +0 -0
  6. package/browser/hooks.js +0 -0
  7. package/browser/index.d.ts +0 -0
  8. package/browser/index.js +0 -0
  9. package/browser/internal/flatten.d.ts +0 -0
  10. package/browser/internal/flatten.js +0 -0
  11. package/browser/internal/formContext.d.ts +0 -0
  12. package/browser/internal/formContext.js +0 -0
  13. package/browser/internal/util.d.ts +0 -0
  14. package/browser/internal/util.js +0 -0
  15. package/browser/server.d.ts +0 -0
  16. package/browser/server.js +0 -0
  17. package/browser/test-data/testFormData.d.ts +0 -0
  18. package/browser/test-data/testFormData.js +0 -0
  19. package/browser/validation/createValidator.d.ts +0 -0
  20. package/browser/validation/createValidator.js +0 -0
  21. package/browser/validation/types.d.ts +0 -0
  22. package/browser/validation/types.js +0 -0
  23. package/browser/validation/validation.test.d.ts +0 -0
  24. package/browser/validation/validation.test.js +0 -0
  25. package/browser/validation/withYup.d.ts +0 -0
  26. package/browser/validation/withYup.js +0 -0
  27. package/browser/validation/withZod.d.ts +0 -0
  28. package/browser/validation/withZod.js +0 -0
  29. package/build/ValidatedForm.d.ts +0 -0
  30. package/build/ValidatedForm.js +0 -0
  31. package/build/hooks.d.ts +0 -0
  32. package/build/hooks.js +0 -0
  33. package/build/index.d.ts +0 -0
  34. package/build/index.js +0 -0
  35. package/build/internal/flatten.d.ts +0 -0
  36. package/build/internal/flatten.js +0 -0
  37. package/build/internal/formContext.d.ts +0 -0
  38. package/build/internal/formContext.js +0 -0
  39. package/build/internal/util.d.ts +0 -0
  40. package/build/internal/util.js +0 -0
  41. package/build/server.d.ts +0 -0
  42. package/build/server.js +0 -0
  43. package/build/test-data/testFormData.d.ts +0 -0
  44. package/build/test-data/testFormData.js +0 -0
  45. package/build/validation/createValidator.d.ts +0 -0
  46. package/build/validation/createValidator.js +0 -0
  47. package/build/validation/types.d.ts +0 -0
  48. package/build/validation/types.js +0 -0
  49. package/build/validation/validation.test.d.ts +0 -0
  50. package/build/validation/validation.test.js +0 -0
  51. package/build/validation/withYup.d.ts +0 -0
  52. package/build/validation/withYup.js +0 -0
  53. package/build/validation/withZod.d.ts +0 -0
  54. package/build/validation/withZod.js +0 -0
  55. package/jest.config.js +5 -0
  56. package/package.json +7 -32
  57. package/src/ValidatedForm.tsx +151 -0
  58. package/src/hooks.ts +60 -0
  59. package/src/index.ts +8 -0
  60. package/src/internal/flatten.ts +48 -0
  61. package/src/internal/formContext.ts +36 -0
  62. package/src/internal/util.ts +23 -0
  63. package/src/server.ts +10 -0
  64. package/src/test-data/testFormData.ts +55 -0
  65. package/src/validation/createValidator.ts +24 -0
  66. package/src/validation/types.ts +26 -0
  67. package/src/validation/validation.test.ts +317 -0
  68. package/src/validation/withYup.ts +43 -0
  69. package/src/validation/withZod.ts +51 -0
  70. package/tsconfig.json +5 -0
  71. package/.eslintcache +0 -1
  72. package/.eslintignore +0 -1
  73. package/.prettierignore +0 -10
  74. package/LICENSE +0 -21
  75. package/README.md +0 -235
  76. package/browser/flatten.d.ts +0 -4
  77. package/browser/flatten.js +0 -35
  78. package/build/flatten.d.ts +0 -4
  79. package/build/flatten.js +0 -43
  80. package/sample-app/.env +0 -7
  81. package/sample-app/README.md +0 -53
  82. package/sample-app/app/components/ErrorBox.tsx +0 -34
  83. package/sample-app/app/components/FormInput.tsx +0 -40
  84. package/sample-app/app/components/FormSelect.tsx +0 -37
  85. package/sample-app/app/components/SubjectForm.tsx +0 -150
  86. package/sample-app/app/entry.client.tsx +0 -4
  87. package/sample-app/app/entry.server.tsx +0 -21
  88. package/sample-app/app/root.tsx +0 -92
  89. package/sample-app/app/routes/index.tsx +0 -5
  90. package/sample-app/app/routes/subjects/$id.edit.tsx +0 -98
  91. package/sample-app/app/routes/subjects/index.tsx +0 -112
  92. package/sample-app/app/routes/subjects/new.tsx +0 -46
  93. package/sample-app/app/services/db.server.ts +0 -23
  94. package/sample-app/app/types.ts +0 -6
  95. package/sample-app/package-lock.json +0 -10890
  96. package/sample-app/package.json +0 -36
  97. package/sample-app/prisma/dev.db +0 -0
  98. package/sample-app/prisma/schema.prisma +0 -34
  99. package/sample-app/public/favicon.ico +0 -0
  100. package/sample-app/remix.config.js +0 -10
  101. package/sample-app/remix.env.d.ts +0 -2
@@ -0,0 +1,9 @@
1
+ $ npm run build:browser && npm run build:main
2
+
3
+ > remix-validated-form@2.0.0 build:browser
4
+ > tsc --module ESNext --outDir ./browser
5
+
6
+
7
+ > remix-validated-form@2.0.0 build:main
8
+ > tsc --module CommonJS --outDir ./build
9
+
File without changes
File without changes
File without changes
File without changes
package/browser/hooks.js CHANGED
File without changes
File without changes
package/browser/index.js CHANGED
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
package/browser/server.js CHANGED
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
package/build/hooks.d.ts CHANGED
File without changes
package/build/hooks.js CHANGED
File without changes
package/build/index.d.ts CHANGED
File without changes
package/build/index.js CHANGED
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
package/build/server.d.ts CHANGED
File without changes
package/build/server.js CHANGED
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
package/jest.config.js CHANGED
@@ -1,5 +1,10 @@
1
1
  /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
2
2
  module.exports = {
3
+ globals: {
4
+ "ts-jest": {
5
+ tsconfig: "tsconfig.json",
6
+ },
7
+ },
3
8
  preset: "ts-jest",
4
9
  testEnvironment: "node",
5
10
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remix-validated-form",
3
- "version": "2.0.0",
3
+ "version": "2.0.1-beta.0",
4
4
  "description": "Form component and utils for easy form validation in remix",
5
5
  "browser": "./browser/index.js",
6
6
  "main": "./build/index.js",
@@ -10,17 +10,12 @@
10
10
  },
11
11
  "sideEffects": false,
12
12
  "scripts": {
13
- "build": "npm run build:browser && npm run build:main && npm run build:tests",
14
- "build:browser": "tsc --project tsconfig.json --module ESNext --outDir ./browser",
15
- "build:main": "tsc --project tsconfig.json --module CommonJS --outDir ./build",
16
- "build:tests": "tsc --project tsconfig.json --module CommonJS --outDir ./test-app/remix-validated-form",
17
- "build:sample": "tsc --project tsconfig.json --module CommonJS --outDir ./sample-app/remix-validated-form",
18
- "sample-app": "npm run build:sample && cd sample-app && npm run dev",
13
+ "dev": "tsc --module ESNext --outDir ./browser --watch",
14
+ "build": "npm run build:browser && npm run build:main",
15
+ "build:browser": "tsc --module ESNext --outDir ./browser",
16
+ "build:main": "tsc --module CommonJS --outDir ./build",
19
17
  "test": "jest src",
20
18
  "test:watch": "jest src --watch",
21
- "lint": "eslint .",
22
- "prettier": "prettier . --write",
23
- "prepare": "husky install",
24
19
  "prepublishOnly": "npm run build:browser && npm run build:main"
25
20
  },
26
21
  "author": {
@@ -48,25 +43,10 @@
48
43
  "@types/jest": "^27.0.3",
49
44
  "@types/lodash": "^4.14.178",
50
45
  "@types/react": "^17.0.37",
51
- "@typescript-eslint/eslint-plugin": "^5.6.0",
52
- "@typescript-eslint/parser": "^5.6.0",
53
- "babel-eslint": "^10.1.0",
54
- "eslint": "^7.32.0",
55
- "eslint-config-react-app": "^6.0.0",
56
- "eslint-plugin-cypress": "^2.12.1",
57
- "eslint-plugin-flowtype": "^8.0.3",
58
- "eslint-plugin-import": "^2.25.3",
59
- "eslint-plugin-jsx-a11y": "^6.5.1",
60
- "eslint-plugin-prettier": "^4.0.0",
61
- "eslint-plugin-react": "^7.27.1",
62
- "eslint-plugin-react-hooks": "^4.3.0",
63
46
  "fetch-blob": "^3.1.3",
64
- "husky": "^7.0.4",
65
- "jest": "^27.4.4",
66
- "lint-staged": "^12.1.2",
67
- "prettier": "^2.5.1",
68
47
  "react": "^17.0.2",
69
48
  "ts-jest": "^27.1.1",
49
+ "tsconfig": "*",
70
50
  "typescript": "^4.5.3",
71
51
  "yup": "^0.32.11",
72
52
  "zod": "^3.11.6"
@@ -75,10 +55,5 @@
75
55
  "lodash": "^4.17.21",
76
56
  "tiny-invariant": "^1.2.0"
77
57
  },
78
- "lint-staged": {
79
- "**/*.{ts,tsx,js,jsx}": [
80
- "prettier --write",
81
- "eslint --cache --fix"
82
- ]
83
- }
58
+ "gitHead": "dab8f221d7c0c5131504215f5c19e3ecdfef97fb"
84
59
  }
@@ -0,0 +1,151 @@
1
+ import {
2
+ Form as RemixForm,
3
+ useActionData,
4
+ useFetcher,
5
+ useFormAction,
6
+ useTransition,
7
+ } from "@remix-run/react";
8
+ import React, {
9
+ ComponentProps,
10
+ useEffect,
11
+ useMemo,
12
+ useRef,
13
+ useState,
14
+ } from "react";
15
+ import invariant from "tiny-invariant";
16
+ import { FormContext, FormContextValue } from "./internal/formContext";
17
+ import { omit, mergeRefs } from "./internal/util";
18
+ import { FieldErrors, Validator } from "./validation/types";
19
+
20
+ export type FormProps<DataType> = {
21
+ /**
22
+ * A `Validator` object that describes how to validate the form.
23
+ */
24
+ validator: Validator<DataType>;
25
+ /**
26
+ * A submit callback that gets called when the form is submitted
27
+ * after all validations have been run.
28
+ */
29
+ onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void;
30
+ /**
31
+ * Allows you to provide a `fetcher` from remix's `useFetcher` hook.
32
+ * The form will use the fetcher for loading states, action data, etc
33
+ * instead of the default form action.
34
+ */
35
+ fetcher?: ReturnType<typeof useFetcher>;
36
+ /**
37
+ * Accepts an object of default values for the form
38
+ * that will automatically be propagated to the form fields via `useField`.
39
+ */
40
+ defaultValues?: Partial<DataType>;
41
+ /**
42
+ * A ref to the form element.
43
+ */
44
+ formRef?: React.RefObject<HTMLFormElement>;
45
+ } & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
46
+
47
+ function useFieldErrors(
48
+ fetcher?: ReturnType<typeof useFetcher>
49
+ ): [FieldErrors, React.Dispatch<React.SetStateAction<FieldErrors>>] {
50
+ const actionData = useActionData<any>();
51
+ const dataToUse = fetcher ? fetcher.data : actionData;
52
+ const fieldErrorsFromAction = dataToUse?.fieldErrors;
53
+
54
+ const [fieldErrors, setFieldErrors] = useState<FieldErrors>(
55
+ fieldErrorsFromAction ?? {}
56
+ );
57
+ useEffect(() => {
58
+ if (fieldErrorsFromAction) setFieldErrors(fieldErrorsFromAction);
59
+ }, [fieldErrorsFromAction]);
60
+
61
+ return [fieldErrors, setFieldErrors];
62
+ }
63
+
64
+ const useIsSubmitting = (
65
+ action?: string,
66
+ fetcher?: ReturnType<typeof useFetcher>
67
+ ) => {
68
+ const actionForCurrentPage = useFormAction();
69
+ const pendingFormSubmit = useTransition().submission;
70
+ return fetcher
71
+ ? fetcher.state === "submitting"
72
+ : pendingFormSubmit &&
73
+ pendingFormSubmit.action === (action ?? actionForCurrentPage);
74
+ };
75
+
76
+ const getDataFromForm = (el: HTMLFormElement) => new FormData(el);
77
+
78
+ /**
79
+ * The primary form component of `remix-validated-form`.
80
+ */
81
+ export function ValidatedForm<DataType>({
82
+ validator,
83
+ onSubmit,
84
+ children,
85
+ fetcher,
86
+ action,
87
+ defaultValues,
88
+ formRef: formRefProp,
89
+ ...rest
90
+ }: FormProps<DataType>) {
91
+ const [fieldErrors, setFieldErrors] = useFieldErrors(fetcher);
92
+ const isSubmitting = useIsSubmitting(action, fetcher);
93
+
94
+ const formRef = useRef<HTMLFormElement>(null);
95
+
96
+ const contextValue = useMemo<FormContextValue>(
97
+ () => ({
98
+ fieldErrors,
99
+ action,
100
+ defaultValues,
101
+ isSubmitting: isSubmitting ?? false,
102
+ clearError: (fieldName) => {
103
+ setFieldErrors((prev) => omit(prev, fieldName));
104
+ },
105
+ validateField: (fieldName) => {
106
+ invariant(formRef.current, "Cannot find reference to form");
107
+ const { error } = validator.validateField(
108
+ getDataFromForm(formRef.current),
109
+ fieldName as any
110
+ );
111
+ if (error) {
112
+ setFieldErrors((prev) => ({
113
+ ...prev,
114
+ [fieldName]: error,
115
+ }));
116
+ }
117
+ },
118
+ }),
119
+ [
120
+ fieldErrors,
121
+ action,
122
+ defaultValues,
123
+ isSubmitting,
124
+ setFieldErrors,
125
+ validator,
126
+ ]
127
+ );
128
+
129
+ const Form = fetcher?.Form ?? RemixForm;
130
+
131
+ return (
132
+ <Form
133
+ ref={mergeRefs([formRef, formRefProp])}
134
+ {...rest}
135
+ action={action}
136
+ onSubmit={(event) => {
137
+ const result = validator.validate(getDataFromForm(event.currentTarget));
138
+ if (result.error) {
139
+ event.preventDefault();
140
+ setFieldErrors(result.error);
141
+ } else {
142
+ onSubmit?.(result.data, event);
143
+ }
144
+ }}
145
+ >
146
+ <FormContext.Provider value={contextValue}>
147
+ {children}
148
+ </FormContext.Provider>
149
+ </Form>
150
+ );
151
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,60 @@
1
+ import get from "lodash/get";
2
+ import toPath from "lodash/toPath";
3
+ import { useContext, useMemo } from "react";
4
+ import { FormContext } from "./internal/formContext";
5
+
6
+ export type FieldProps = {
7
+ /**
8
+ * The validation error message if there is one.
9
+ */
10
+ error?: string;
11
+ /**
12
+ * Clears the error message.
13
+ */
14
+ clearError: () => void;
15
+ /**
16
+ * Validates the field.
17
+ */
18
+ validate: () => void;
19
+ /**
20
+ * The default value of the field, if there is one.
21
+ */
22
+ defaultValue?: any;
23
+ };
24
+
25
+ /**
26
+ * Provides the data and helpers necessary to set up a field.
27
+ */
28
+ export const useField = (name: string): FieldProps => {
29
+ const { fieldErrors, clearError, validateField, defaultValues } =
30
+ useContext(FormContext);
31
+
32
+ const field = useMemo<FieldProps>(
33
+ () => ({
34
+ error: fieldErrors[name],
35
+ clearError: () => {
36
+ clearError(name);
37
+ },
38
+ validate: () => validateField(name),
39
+ defaultValue: defaultValues
40
+ ? get(defaultValues, toPath(name), undefined)
41
+ : undefined,
42
+ }),
43
+ [clearError, defaultValues, fieldErrors, name, validateField]
44
+ );
45
+
46
+ return field;
47
+ };
48
+
49
+ /**
50
+ * Provides access to the entire form context.
51
+ * This is not usually necessary, but can be useful for advanced use cases.
52
+ */
53
+ export const useFormContext = () => useContext(FormContext);
54
+
55
+ /**
56
+ * Returns whether or not the parent form is currently being submitted.
57
+ * This is different from remix's `useTransition().submission` in that it
58
+ * is aware of what form it's in and when _that_ form is being submitted.
59
+ */
60
+ export const useIsSubmitting = () => useFormContext().isSubmitting;
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from "./hooks";
2
+ export * from "./server";
3
+ export * from "./ValidatedForm";
4
+ export * from "./validation/types";
5
+ export * from "./validation/withYup";
6
+ export * from "./validation/withZod";
7
+ export * from "./validation/createValidator";
8
+ export type { FormContextValue } from "./internal/formContext";
@@ -0,0 +1,48 @@
1
+ // `flatten` is taken from https://github.com/richie5um/FlattenJS. Decided to implement them here instead of using that package because this is a core functionality of the library and this will add more flexibility in case we need to change the implementation.
2
+ import assign from "lodash/assign";
3
+ import isArray from "lodash/isArray";
4
+ import isObject from "lodash/isObject";
5
+ import keys from "lodash/keys";
6
+ import mapKeys from "lodash/mapKeys";
7
+ import set from "lodash/set";
8
+ import transform from "lodash/transform";
9
+ import { GenericObject } from "..";
10
+
11
+ export const objectFromPathEntries = (entries: [string, any][]) =>
12
+ entries.reduce((acc, [key, value]) => set(acc, key, value), {});
13
+
14
+ /** Flatten an object so there are no nested objects or arrays */
15
+ export function flatten(obj: GenericObject, preserveEmpty = false) {
16
+ return transform(
17
+ obj,
18
+ function (result: GenericObject, value, key) {
19
+ if (isObject(value)) {
20
+ let flatMap = mapKeys(
21
+ flatten(value, preserveEmpty),
22
+ function (_mvalue, mkey) {
23
+ if (isArray(value)) {
24
+ let index = mkey.indexOf(".");
25
+ if (-1 !== index) {
26
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
27
+ }
28
+ return `${key}[${mkey}]`;
29
+ }
30
+ return `${key}.${mkey}`;
31
+ }
32
+ );
33
+
34
+ assign(result, flatMap);
35
+
36
+ // Preverve Empty arrays and objects
37
+ if (preserveEmpty && keys(flatMap).length === 0) {
38
+ result[key] = value;
39
+ }
40
+ } else {
41
+ result[key] = value;
42
+ }
43
+
44
+ return result;
45
+ },
46
+ {}
47
+ );
48
+ }
@@ -0,0 +1,36 @@
1
+ import { createContext } from "react";
2
+ import { FieldErrors } from "../validation/types";
3
+
4
+ export type FormContextValue = {
5
+ /**
6
+ * All the errors in all the fields in the form.
7
+ */
8
+ fieldErrors: FieldErrors;
9
+ /**
10
+ * Clear the errors of the specified fields.
11
+ */
12
+ clearError: (...names: string[]) => void;
13
+ /**
14
+ * Validate the specified field.
15
+ */
16
+ validateField: (fieldName: string) => void;
17
+ /**
18
+ * The `action` prop of the form.
19
+ */
20
+ action?: string;
21
+ /**
22
+ * Whether or not the form is submitting.
23
+ */
24
+ isSubmitting: boolean;
25
+ /**
26
+ * The default values of the form.
27
+ */
28
+ defaultValues?: { [fieldName: string]: any };
29
+ };
30
+
31
+ export const FormContext = createContext<FormContextValue>({
32
+ fieldErrors: {},
33
+ clearError: () => {},
34
+ validateField: () => {},
35
+ isSubmitting: false,
36
+ });
@@ -0,0 +1,23 @@
1
+ import type React from "react";
2
+
3
+ export const omit = (obj: any, ...keys: string[]) => {
4
+ const result = { ...obj };
5
+ for (const key of keys) {
6
+ delete result[key];
7
+ }
8
+ return result;
9
+ };
10
+
11
+ export const mergeRefs = <T = any>(
12
+ refs: Array<React.MutableRefObject<T> | React.LegacyRef<T> | undefined>
13
+ ): React.RefCallback<T> => {
14
+ return (value: T) => {
15
+ refs.filter(Boolean).forEach((ref) => {
16
+ if (typeof ref === "function") {
17
+ ref(value);
18
+ } else if (ref != null) {
19
+ (ref as React.MutableRefObject<T | null>).current = value;
20
+ }
21
+ });
22
+ };
23
+ };
package/src/server.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { json } from "@remix-run/server-runtime";
2
+ import { FieldErrors } from "./validation/types";
3
+
4
+ /**
5
+ * Takes the errors from a `Validator` and returns a `Response`.
6
+ * The `ValidatedForm` on the frontend will automatically display the errors
7
+ * if this is returned from the action.
8
+ */
9
+ export const validationError = (errors: FieldErrors) =>
10
+ json({ fieldErrors: errors }, { status: 422 });
@@ -0,0 +1,55 @@
1
+ // Copied from remix to use in tests
2
+ // https://github.com/remix-run/remix/blob/a69a631cb5add72d5fb24211ab2a0be367b6f2fd/packages/remix-node/form-data.ts
3
+ export class TestFormData implements FormData {
4
+ private _params: URLSearchParams;
5
+
6
+ constructor(body?: string) {
7
+ this._params = new URLSearchParams(body);
8
+ }
9
+ append(name: string, value: string | Blob, fileName?: string): void {
10
+ if (typeof value !== "string") {
11
+ throw new Error("formData.append can only accept a string");
12
+ }
13
+ this._params.append(name, value);
14
+ }
15
+ delete(name: string): void {
16
+ this._params.delete(name);
17
+ }
18
+ get(name: string): FormDataEntryValue | null {
19
+ return this._params.get(name);
20
+ }
21
+ getAll(name: string): FormDataEntryValue[] {
22
+ return this._params.getAll(name);
23
+ }
24
+ has(name: string): boolean {
25
+ return this._params.has(name);
26
+ }
27
+ set(name: string, value: string | Blob, fileName?: string): void {
28
+ if (typeof value !== "string") {
29
+ throw new Error("formData.set can only accept a string");
30
+ }
31
+ this._params.set(name, value);
32
+ }
33
+ forEach(
34
+ callbackfn: (
35
+ value: FormDataEntryValue,
36
+ key: string,
37
+ parent: FormData
38
+ ) => void,
39
+ thisArg?: any
40
+ ): void {
41
+ this._params.forEach(callbackfn, thisArg);
42
+ }
43
+ entries(): IterableIterator<[string, FormDataEntryValue]> {
44
+ return this._params.entries();
45
+ }
46
+ keys(): IterableIterator<string> {
47
+ return this._params.keys();
48
+ }
49
+ values(): IterableIterator<FormDataEntryValue> {
50
+ return this._params.values();
51
+ }
52
+ *[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]> {
53
+ yield* this._params;
54
+ }
55
+ }
@@ -0,0 +1,24 @@
1
+ import { GenericObject, Validator } from "..";
2
+ import { objectFromPathEntries } from "../internal/flatten";
3
+
4
+ const preprocessFormData = (data: GenericObject | FormData): GenericObject => {
5
+ // A slightly janky way of determining if the data is a FormData object
6
+ // since node doesn't really have FormData
7
+ if ("entries" in data && typeof data.entries === "function")
8
+ return objectFromPathEntries([...data.entries()]);
9
+ return objectFromPathEntries(Object.entries(data));
10
+ };
11
+
12
+ /**
13
+ * Used to create a validator for a form.
14
+ * It provides built-in handling for unflattening nested objects and
15
+ * extracting the values from FormData.
16
+ */
17
+ export function createValidator<T>(validator: Validator<T>): Validator<T> {
18
+ return {
19
+ validate: (value: GenericObject | FormData) =>
20
+ validator.validate(preprocessFormData(value)),
21
+ validateField: (data: GenericObject | FormData, field: string) =>
22
+ validator.validateField(preprocessFormData(data), field),
23
+ };
24
+ }