remix-validated-form 1.1.1 → 2.0.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 (72) hide show
  1. package/.eslintcache +1 -1
  2. package/.prettierignore +2 -0
  3. package/README.md +72 -19
  4. package/browser/ValidatedForm.d.ts +22 -0
  5. package/browser/ValidatedForm.js +5 -2
  6. package/browser/flatten.d.ts +4 -0
  7. package/browser/flatten.js +35 -0
  8. package/browser/hooks.d.ts +28 -3
  9. package/browser/hooks.js +17 -2
  10. package/browser/index.d.ts +2 -0
  11. package/browser/index.js +1 -0
  12. package/browser/internal/flatten.d.ts +4 -0
  13. package/browser/internal/flatten.js +35 -0
  14. package/browser/internal/formContext.d.ts +18 -0
  15. package/browser/server.d.ts +5 -0
  16. package/browser/server.js +5 -0
  17. package/browser/test-data/testFormData.d.ts +15 -0
  18. package/browser/test-data/testFormData.js +46 -0
  19. package/browser/validation/createValidator.d.ts +7 -0
  20. package/browser/validation/createValidator.js +19 -0
  21. package/browser/validation/types.d.ts +14 -2
  22. package/browser/validation/validation.test.js +157 -8
  23. package/browser/validation/withYup.d.ts +3 -0
  24. package/browser/validation/withYup.js +31 -25
  25. package/browser/validation/withZod.d.ts +3 -0
  26. package/browser/validation/withZod.js +19 -4
  27. package/build/ValidatedForm.d.ts +22 -0
  28. package/build/ValidatedForm.js +5 -2
  29. package/build/flatten.d.ts +4 -0
  30. package/build/flatten.js +43 -0
  31. package/build/hooks.d.ts +28 -3
  32. package/build/hooks.js +20 -2
  33. package/build/index.d.ts +2 -0
  34. package/build/index.js +1 -0
  35. package/build/internal/flatten.d.ts +4 -0
  36. package/build/internal/flatten.js +43 -0
  37. package/build/internal/formContext.d.ts +18 -0
  38. package/build/server.d.ts +5 -0
  39. package/build/server.js +5 -0
  40. package/build/test-data/testFormData.d.ts +15 -0
  41. package/build/test-data/testFormData.js +50 -0
  42. package/build/validation/createValidator.d.ts +7 -0
  43. package/build/validation/createValidator.js +23 -0
  44. package/build/validation/types.d.ts +14 -2
  45. package/build/validation/validation.test.js +157 -8
  46. package/build/validation/withYup.d.ts +3 -0
  47. package/build/validation/withYup.js +31 -25
  48. package/build/validation/withZod.d.ts +3 -0
  49. package/build/validation/withZod.js +22 -4
  50. package/package.json +18 -13
  51. package/sample-app/.env +7 -0
  52. package/sample-app/README.md +53 -0
  53. package/sample-app/app/components/ErrorBox.tsx +34 -0
  54. package/sample-app/app/components/FormInput.tsx +40 -0
  55. package/sample-app/app/components/FormSelect.tsx +37 -0
  56. package/sample-app/app/components/SubjectForm.tsx +150 -0
  57. package/sample-app/app/entry.client.tsx +4 -0
  58. package/sample-app/app/entry.server.tsx +21 -0
  59. package/sample-app/app/root.tsx +92 -0
  60. package/sample-app/app/routes/index.tsx +5 -0
  61. package/sample-app/app/routes/subjects/$id.edit.tsx +98 -0
  62. package/sample-app/app/routes/subjects/index.tsx +112 -0
  63. package/sample-app/app/routes/subjects/new.tsx +46 -0
  64. package/sample-app/app/services/db.server.ts +23 -0
  65. package/sample-app/app/types.ts +6 -0
  66. package/sample-app/package-lock.json +10890 -0
  67. package/sample-app/package.json +36 -0
  68. package/sample-app/prisma/dev.db +0 -0
  69. package/sample-app/prisma/schema.prisma +34 -0
  70. package/sample-app/public/favicon.ico +0 -0
  71. package/sample-app/remix.config.js +10 -0
  72. package/sample-app/remix.env.d.ts +2 -0
@@ -1,6 +1,7 @@
1
1
  import * as yup from "yup";
2
2
  import { z } from "zod";
3
3
  import { withYup } from "..";
4
+ import { TestFormData } from "../test-data/testFormData";
4
5
  import { withZod } from "./withZod";
5
6
  const validationTestCases = [
6
7
  {
@@ -9,6 +10,17 @@ const validationTestCases = [
9
10
  firstName: yup.string().required(),
10
11
  lastName: yup.string().required(),
11
12
  age: yup.number(),
13
+ address: yup
14
+ .object({
15
+ streetAddress: yup.string().required(),
16
+ city: yup.string().required(),
17
+ country: yup.string().required(),
18
+ })
19
+ .required(),
20
+ pets: yup.array().of(yup.object({
21
+ animal: yup.string().required(),
22
+ name: yup.string().required(),
23
+ })),
12
24
  })),
13
25
  },
14
26
  {
@@ -17,6 +29,18 @@ const validationTestCases = [
17
29
  firstName: z.string().nonempty(),
18
30
  lastName: z.string().nonempty(),
19
31
  age: z.optional(z.number()),
32
+ address: z.preprocess((value) => (value == null ? {} : value), z.object({
33
+ streetAddress: z.string().nonempty(),
34
+ city: z.string().nonempty(),
35
+ country: z.string().nonempty(),
36
+ })),
37
+ pets: z
38
+ .object({
39
+ animal: z.string().nonempty(),
40
+ name: z.string().nonempty(),
41
+ })
42
+ .array()
43
+ .optional(),
20
44
  })),
21
45
  },
22
46
  ];
@@ -26,41 +50,166 @@ describe("Validation", () => {
26
50
  describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
27
51
  describe("validate", () => {
28
52
  it("should return the data when valid", () => {
29
- const obj = {
53
+ const person = {
30
54
  firstName: "John",
31
55
  lastName: "Doe",
32
56
  age: 30,
57
+ address: {
58
+ streetAddress: "123 Main St",
59
+ city: "Anytown",
60
+ country: "USA",
61
+ },
62
+ pets: [{ animal: "dog", name: "Fido" }],
33
63
  };
34
- expect(validator.validate(obj)).toEqual({
35
- data: obj,
64
+ expect(validator.validate(person)).toEqual({
65
+ data: person,
36
66
  error: undefined,
37
67
  });
38
68
  });
39
69
  it("should return field errors when invalid", () => {
40
- const obj = { age: "hi!" };
70
+ const obj = { age: "hi!", pets: [{ animal: "dog" }] };
41
71
  expect(validator.validate(obj)).toEqual({
42
72
  data: undefined,
43
73
  error: {
44
74
  firstName: anyString,
45
75
  lastName: anyString,
46
76
  age: anyString,
77
+ "address.city": anyString,
78
+ "address.country": anyString,
79
+ "address.streetAddress": anyString,
80
+ "pets[0].name": anyString,
81
+ },
82
+ });
83
+ });
84
+ it("should unflatten data when validating", () => {
85
+ const data = {
86
+ firstName: "John",
87
+ lastName: "Doe",
88
+ age: 30,
89
+ "address.streetAddress": "123 Main St",
90
+ "address.city": "Anytown",
91
+ "address.country": "USA",
92
+ "pets[0].animal": "dog",
93
+ "pets[0].name": "Fido",
94
+ };
95
+ expect(validator.validate(data)).toEqual({
96
+ data: {
97
+ firstName: "John",
98
+ lastName: "Doe",
99
+ age: 30,
100
+ address: {
101
+ streetAddress: "123 Main St",
102
+ city: "Anytown",
103
+ country: "USA",
104
+ },
105
+ pets: [{ animal: "dog", name: "Fido" }],
106
+ },
107
+ error: undefined,
108
+ });
109
+ });
110
+ it("should accept FormData directly and return errors", () => {
111
+ const formData = new TestFormData();
112
+ formData.set("firstName", "John");
113
+ formData.set("lastName", "Doe");
114
+ formData.set("address.streetAddress", "123 Main St");
115
+ formData.set("address.country", "USA");
116
+ formData.set("pets[0].animal", "dog");
117
+ expect(validator.validate(formData)).toEqual({
118
+ data: undefined,
119
+ error: {
120
+ "address.city": anyString,
121
+ "pets[0].name": anyString,
47
122
  },
48
123
  });
49
124
  });
125
+ it("should accept FormData directly and return valid data", () => {
126
+ const formData = new TestFormData();
127
+ formData.set("firstName", "John");
128
+ formData.set("lastName", "Doe");
129
+ formData.set("address.streetAddress", "123 Main St");
130
+ formData.set("address.country", "USA");
131
+ formData.set("address.city", "Anytown");
132
+ formData.set("pets[0].animal", "dog");
133
+ formData.set("pets[0].name", "Fido");
134
+ expect(validator.validate(formData)).toEqual({
135
+ data: {
136
+ firstName: "John",
137
+ lastName: "Doe",
138
+ address: {
139
+ streetAddress: "123 Main St",
140
+ country: "USA",
141
+ city: "Anytown",
142
+ },
143
+ pets: [{ animal: "dog", name: "Fido" }],
144
+ },
145
+ error: undefined,
146
+ });
147
+ });
50
148
  });
51
149
  describe("validateField", () => {
52
150
  it("should not return an error if field is valid", () => {
53
- const obj = {
151
+ const person = {
54
152
  firstName: "John",
55
153
  lastName: {}, // invalid, but we should only be validating firstName
56
154
  };
57
- expect(validator.validateField(obj, "firstName")).toEqual({
155
+ expect(validator.validateField(person, "firstName")).toEqual({
156
+ error: undefined,
157
+ });
158
+ });
159
+ it("should not return an error if a nested field is valid", () => {
160
+ const person = {
161
+ firstName: "John",
162
+ lastName: {},
163
+ address: {
164
+ streetAddress: "123 Main St",
165
+ city: "Anytown",
166
+ country: "USA",
167
+ },
168
+ pets: [{ animal: "dog", name: "Fido" }],
169
+ };
170
+ expect(validator.validateField(person, "address.streetAddress")).toEqual({
171
+ error: undefined,
172
+ });
173
+ expect(validator.validateField(person, "address.city")).toEqual({
174
+ error: undefined,
175
+ });
176
+ expect(validator.validateField(person, "address.country")).toEqual({
177
+ error: undefined,
178
+ });
179
+ expect(validator.validateField(person, "pets[0].animal")).toEqual({
180
+ error: undefined,
181
+ });
182
+ expect(validator.validateField(person, "pets[0].name")).toEqual({
58
183
  error: undefined,
59
184
  });
60
185
  });
61
186
  it("should return an error if field is invalid", () => {
62
- const obj = { firstName: "John", lastName: {} };
63
- expect(validator.validateField(obj, "lastName")).toEqual({
187
+ const person = {
188
+ firstName: "John",
189
+ lastName: {},
190
+ address: {
191
+ streetAddress: "123 Main St",
192
+ city: 1234,
193
+ },
194
+ };
195
+ expect(validator.validateField(person, "lastName")).toEqual({
196
+ error: anyString,
197
+ });
198
+ });
199
+ it("should return an error if a nested field is invalid", () => {
200
+ const person = {
201
+ firstName: "John",
202
+ lastName: {},
203
+ address: {
204
+ streetAddress: "123 Main St",
205
+ city: 1234,
206
+ },
207
+ pets: [{ animal: "dog" }],
208
+ };
209
+ expect(validator.validateField(person, "address.country")).toEqual({
210
+ error: anyString,
211
+ });
212
+ expect(validator.validateField(person, "pets[0].name")).toEqual({
64
213
  error: anyString,
65
214
  });
66
215
  });
@@ -1,3 +1,6 @@
1
1
  import type { AnyObjectSchema, InferType } from "yup";
2
2
  import { Validator } from "./types";
3
+ /**
4
+ * Create a `Validator` using a `yup` schema.
5
+ */
3
6
  export declare const withYup: <Schema extends AnyObjectSchema>(validationSchema: Schema) => Validator<InferType<Schema>>;
@@ -1,3 +1,4 @@
1
+ import { createValidator } from "./createValidator";
1
2
  const validationErrorToFieldErrors = (error) => {
2
3
  const fieldErrors = {};
3
4
  error.inner.forEach((innerError) => {
@@ -7,28 +8,33 @@ const validationErrorToFieldErrors = (error) => {
7
8
  });
8
9
  return fieldErrors;
9
10
  };
10
- export const withYup = (validationSchema) => ({
11
- validate: (data) => {
12
- try {
13
- const validated = validationSchema.validateSync(data, {
14
- abortEarly: false,
15
- });
16
- return { data: validated, error: undefined };
17
- }
18
- catch (err) {
19
- return {
20
- error: validationErrorToFieldErrors(err),
21
- data: undefined,
22
- };
23
- }
24
- },
25
- validateField: (data, field) => {
26
- try {
27
- validationSchema.validateSyncAt(field, data);
28
- return {};
29
- }
30
- catch (err) {
31
- return { error: err.message };
32
- }
33
- },
34
- });
11
+ /**
12
+ * Create a `Validator` using a `yup` schema.
13
+ */
14
+ export const withYup = (validationSchema) => {
15
+ return createValidator({
16
+ validate: (data) => {
17
+ try {
18
+ const validated = validationSchema.validateSync(data, {
19
+ abortEarly: false,
20
+ });
21
+ return { data: validated, error: undefined };
22
+ }
23
+ catch (err) {
24
+ return {
25
+ error: validationErrorToFieldErrors(err),
26
+ data: undefined,
27
+ };
28
+ }
29
+ },
30
+ validateField: (data, field) => {
31
+ try {
32
+ validationSchema.validateSyncAt(field, data);
33
+ return {};
34
+ }
35
+ catch (err) {
36
+ return { error: err.message };
37
+ }
38
+ },
39
+ });
40
+ };
@@ -1,3 +1,6 @@
1
1
  import type { z } from "zod";
2
2
  import { Validator } from "..";
3
+ /**
4
+ * Create a validator using a `zod` schema.
5
+ */
3
6
  export declare function withZod<T>(zodSchema: z.Schema<T>): Validator<T>;
@@ -1,3 +1,6 @@
1
+ import isEqual from "lodash/isEqual";
2
+ import toPath from "lodash/toPath";
3
+ import { createValidator } from "./createValidator";
1
4
  const getIssuesForError = (err) => {
2
5
  return err.issues.flatMap((issue) => {
3
6
  if ("unionErrors" in issue) {
@@ -8,15 +11,24 @@ const getIssuesForError = (err) => {
8
11
  }
9
12
  });
10
13
  };
14
+ function pathToString(array) {
15
+ return array.reduce(function (string, item) {
16
+ var prefix = string === "" ? "" : ".";
17
+ return string + (isNaN(Number(item)) ? prefix + item : "[" + item + "]");
18
+ }, "");
19
+ }
20
+ /**
21
+ * Create a validator using a `zod` schema.
22
+ */
11
23
  export function withZod(zodSchema) {
12
- return {
24
+ return createValidator({
13
25
  validate: (value) => {
14
26
  const result = zodSchema.safeParse(value);
15
27
  if (result.success)
16
28
  return { data: result.data, error: undefined };
17
29
  const fieldErrors = {};
18
30
  getIssuesForError(result.error).forEach((issue) => {
19
- const path = issue.path.join(".");
31
+ const path = pathToString(issue.path);
20
32
  if (!fieldErrors[path])
21
33
  fieldErrors[path] = issue.message;
22
34
  });
@@ -28,8 +40,11 @@ export function withZod(zodSchema) {
28
40
  if (result.success)
29
41
  return { error: undefined };
30
42
  return {
31
- error: (_a = getIssuesForError(result.error).find((issue) => issue.path.join(".") === field)) === null || _a === void 0 ? void 0 : _a.message,
43
+ error: (_a = getIssuesForError(result.error).find((issue) => {
44
+ const allPathsAsString = issue.path.map((p) => `${p}`);
45
+ return isEqual(allPathsAsString, toPath(field));
46
+ })) === null || _a === void 0 ? void 0 : _a.message,
32
47
  };
33
48
  },
34
- };
49
+ });
35
50
  }
@@ -2,10 +2,32 @@ import { Form as RemixForm, useFetcher } from "@remix-run/react";
2
2
  import React, { ComponentProps } from "react";
3
3
  import { Validator } from "./validation/types";
4
4
  export declare type FormProps<DataType> = {
5
+ /**
6
+ * A `Validator` object that describes how to validate the form.
7
+ */
5
8
  validator: Validator<DataType>;
9
+ /**
10
+ * A submit callback that gets called when the form is submitted
11
+ * after all validations have been run.
12
+ */
6
13
  onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void;
14
+ /**
15
+ * Allows you to provide a `fetcher` from remix's `useFetcher` hook.
16
+ * The form will use the fetcher for loading states, action data, etc
17
+ * instead of the default form action.
18
+ */
7
19
  fetcher?: ReturnType<typeof useFetcher>;
20
+ /**
21
+ * Accepts an object of default values for the form
22
+ * that will automatically be propagated to the form fields via `useField`.
23
+ */
8
24
  defaultValues?: Partial<DataType>;
25
+ /**
26
+ * A ref to the form element.
27
+ */
9
28
  formRef?: React.RefObject<HTMLFormElement>;
10
29
  } & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
30
+ /**
31
+ * The primary form component of `remix-validated-form`.
32
+ */
11
33
  export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }: FormProps<DataType>): JSX.Element;
@@ -27,9 +27,12 @@ const useIsSubmitting = (action, fetcher) => {
27
27
  return fetcher
28
28
  ? fetcher.state === "submitting"
29
29
  : pendingFormSubmit &&
30
- pendingFormSubmit.action.endsWith(action !== null && action !== void 0 ? action : actionForCurrentPage);
30
+ pendingFormSubmit.action === (action !== null && action !== void 0 ? action : actionForCurrentPage);
31
31
  };
32
- const getDataFromForm = (el) => Object.fromEntries(new FormData(el));
32
+ const getDataFromForm = (el) => new FormData(el);
33
+ /**
34
+ * The primary form component of `remix-validated-form`.
35
+ */
33
36
  function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
34
37
  var _a;
35
38
  const [fieldErrors, setFieldErrors] = useFieldErrors(fetcher);
@@ -0,0 +1,4 @@
1
+ import { GenericObject } from ".";
2
+ export declare const objectFromPathEntries: (entries: [string, any][]) => {};
3
+ /** Flatten an object so there are no nested objects or arrays */
4
+ export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.flatten = exports.objectFromPathEntries = void 0;
7
+ // `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.
8
+ const assign_1 = __importDefault(require("lodash/assign"));
9
+ const isArray_1 = __importDefault(require("lodash/isArray"));
10
+ const isObject_1 = __importDefault(require("lodash/isObject"));
11
+ const keys_1 = __importDefault(require("lodash/keys"));
12
+ const mapKeys_1 = __importDefault(require("lodash/mapKeys"));
13
+ const set_1 = __importDefault(require("lodash/set"));
14
+ const transform_1 = __importDefault(require("lodash/transform"));
15
+ const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => (0, set_1.default)(acc, key, value), {});
16
+ exports.objectFromPathEntries = objectFromPathEntries;
17
+ /** Flatten an object so there are no nested objects or arrays */
18
+ function flatten(obj, preserveEmpty = false) {
19
+ return (0, transform_1.default)(obj, function (result, value, key) {
20
+ if ((0, isObject_1.default)(value)) {
21
+ let flatMap = (0, mapKeys_1.default)(flatten(value, preserveEmpty), function (_mvalue, mkey) {
22
+ if ((0, isArray_1.default)(value)) {
23
+ let index = mkey.indexOf(".");
24
+ if (-1 !== index) {
25
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
26
+ }
27
+ return `${key}[${mkey}]`;
28
+ }
29
+ return `${key}.${mkey}`;
30
+ });
31
+ (0, assign_1.default)(result, flatMap);
32
+ // Preverve Empty arrays and objects
33
+ if (preserveEmpty && (0, keys_1.default)(flatMap).length === 0) {
34
+ result[key] = value;
35
+ }
36
+ }
37
+ else {
38
+ result[key] = value;
39
+ }
40
+ return result;
41
+ }, {});
42
+ }
43
+ exports.flatten = flatten;
package/build/hooks.d.ts CHANGED
@@ -1,8 +1,33 @@
1
- export declare const useField: (name: string) => {
2
- error: string;
1
+ export declare type FieldProps = {
2
+ /**
3
+ * The validation error message if there is one.
4
+ */
5
+ error?: string;
6
+ /**
7
+ * Clears the error message.
8
+ */
3
9
  clearError: () => void;
10
+ /**
11
+ * Validates the field.
12
+ */
4
13
  validate: () => void;
5
- defaultValue: any;
14
+ /**
15
+ * The default value of the field, if there is one.
16
+ */
17
+ defaultValue?: any;
6
18
  };
19
+ /**
20
+ * Provides the data and helpers necessary to set up a field.
21
+ */
22
+ export declare const useField: (name: string) => FieldProps;
23
+ /**
24
+ * Provides access to the entire form context.
25
+ * This is not usually necessary, but can be useful for advanced use cases.
26
+ */
7
27
  export declare const useFormContext: () => import("./internal/formContext").FormContextValue;
28
+ /**
29
+ * Returns whether or not the parent form is currently being submitted.
30
+ * This is different from remix's `useTransition().submission` in that it
31
+ * is aware of what form it's in and when _that_ form is being submitted.
32
+ */
8
33
  export declare const useIsSubmitting: () => boolean;
package/build/hooks.js CHANGED
@@ -1,8 +1,16 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.useIsSubmitting = exports.useFormContext = exports.useField = void 0;
7
+ const get_1 = __importDefault(require("lodash/get"));
8
+ const toPath_1 = __importDefault(require("lodash/toPath"));
4
9
  const react_1 = require("react");
5
10
  const formContext_1 = require("./internal/formContext");
11
+ /**
12
+ * Provides the data and helpers necessary to set up a field.
13
+ */
6
14
  const useField = (name) => {
7
15
  const { fieldErrors, clearError, validateField, defaultValues } = (0, react_1.useContext)(formContext_1.FormContext);
8
16
  const field = (0, react_1.useMemo)(() => ({
@@ -11,13 +19,23 @@ const useField = (name) => {
11
19
  clearError(name);
12
20
  },
13
21
  validate: () => validateField(name),
14
- defaultValue: defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues[name],
22
+ defaultValue: defaultValues
23
+ ? (0, get_1.default)(defaultValues, (0, toPath_1.default)(name), undefined)
24
+ : undefined,
15
25
  }), [clearError, defaultValues, fieldErrors, name, validateField]);
16
26
  return field;
17
27
  };
18
28
  exports.useField = useField;
19
- // test commit
29
+ /**
30
+ * Provides access to the entire form context.
31
+ * This is not usually necessary, but can be useful for advanced use cases.
32
+ */
20
33
  const useFormContext = () => (0, react_1.useContext)(formContext_1.FormContext);
21
34
  exports.useFormContext = useFormContext;
35
+ /**
36
+ * Returns whether or not the parent form is currently being submitted.
37
+ * This is different from remix's `useTransition().submission` in that it
38
+ * is aware of what form it's in and when _that_ form is being submitted.
39
+ */
22
40
  const useIsSubmitting = () => (0, exports.useFormContext)().isSubmitting;
23
41
  exports.useIsSubmitting = useIsSubmitting;
package/build/index.d.ts CHANGED
@@ -4,3 +4,5 @@ export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/withYup";
6
6
  export * from "./validation/withZod";
7
+ export * from "./validation/createValidator";
8
+ export type { FormContextValue } from "./internal/formContext";
package/build/index.js CHANGED
@@ -16,3 +16,4 @@ __exportStar(require("./ValidatedForm"), exports);
16
16
  __exportStar(require("./validation/types"), exports);
17
17
  __exportStar(require("./validation/withYup"), exports);
18
18
  __exportStar(require("./validation/withZod"), exports);
19
+ __exportStar(require("./validation/createValidator"), exports);
@@ -0,0 +1,4 @@
1
+ import { GenericObject } from "..";
2
+ export declare const objectFromPathEntries: (entries: [string, any][]) => {};
3
+ /** Flatten an object so there are no nested objects or arrays */
4
+ export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.flatten = exports.objectFromPathEntries = void 0;
7
+ // `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.
8
+ const assign_1 = __importDefault(require("lodash/assign"));
9
+ const isArray_1 = __importDefault(require("lodash/isArray"));
10
+ const isObject_1 = __importDefault(require("lodash/isObject"));
11
+ const keys_1 = __importDefault(require("lodash/keys"));
12
+ const mapKeys_1 = __importDefault(require("lodash/mapKeys"));
13
+ const set_1 = __importDefault(require("lodash/set"));
14
+ const transform_1 = __importDefault(require("lodash/transform"));
15
+ const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => (0, set_1.default)(acc, key, value), {});
16
+ exports.objectFromPathEntries = objectFromPathEntries;
17
+ /** Flatten an object so there are no nested objects or arrays */
18
+ function flatten(obj, preserveEmpty = false) {
19
+ return (0, transform_1.default)(obj, function (result, value, key) {
20
+ if ((0, isObject_1.default)(value)) {
21
+ let flatMap = (0, mapKeys_1.default)(flatten(value, preserveEmpty), function (_mvalue, mkey) {
22
+ if ((0, isArray_1.default)(value)) {
23
+ let index = mkey.indexOf(".");
24
+ if (-1 !== index) {
25
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
26
+ }
27
+ return `${key}[${mkey}]`;
28
+ }
29
+ return `${key}.${mkey}`;
30
+ });
31
+ (0, assign_1.default)(result, flatMap);
32
+ // Preverve Empty arrays and objects
33
+ if (preserveEmpty && (0, keys_1.default)(flatMap).length === 0) {
34
+ result[key] = value;
35
+ }
36
+ }
37
+ else {
38
+ result[key] = value;
39
+ }
40
+ return result;
41
+ }, {});
42
+ }
43
+ exports.flatten = flatten;
@@ -1,11 +1,29 @@
1
1
  /// <reference types="react" />
2
2
  import { FieldErrors } from "../validation/types";
3
3
  export declare type FormContextValue = {
4
+ /**
5
+ * All the errors in all the fields in the form.
6
+ */
4
7
  fieldErrors: FieldErrors;
8
+ /**
9
+ * Clear the errors of the specified fields.
10
+ */
5
11
  clearError: (...names: string[]) => void;
12
+ /**
13
+ * Validate the specified field.
14
+ */
6
15
  validateField: (fieldName: string) => void;
16
+ /**
17
+ * The `action` prop of the form.
18
+ */
7
19
  action?: string;
20
+ /**
21
+ * Whether or not the form is submitting.
22
+ */
8
23
  isSubmitting: boolean;
24
+ /**
25
+ * The default values of the form.
26
+ */
9
27
  defaultValues?: {
10
28
  [fieldName: string]: any;
11
29
  };
package/build/server.d.ts CHANGED
@@ -1,2 +1,7 @@
1
1
  import { FieldErrors } from "./validation/types";
2
+ /**
3
+ * Takes the errors from a `Validator` and returns a `Response`.
4
+ * The `ValidatedForm` on the frontend will automatically display the errors
5
+ * if this is returned from the action.
6
+ */
2
7
  export declare const validationError: (errors: FieldErrors) => Response;
package/build/server.js CHANGED
@@ -2,5 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validationError = void 0;
4
4
  const server_runtime_1 = require("@remix-run/server-runtime");
5
+ /**
6
+ * Takes the errors from a `Validator` and returns a `Response`.
7
+ * The `ValidatedForm` on the frontend will automatically display the errors
8
+ * if this is returned from the action.
9
+ */
5
10
  const validationError = (errors) => (0, server_runtime_1.json)({ fieldErrors: errors }, { status: 422 });
6
11
  exports.validationError = validationError;
@@ -0,0 +1,15 @@
1
+ export declare class TestFormData implements FormData {
2
+ private _params;
3
+ constructor(body?: string);
4
+ append(name: string, value: string | Blob, fileName?: string): void;
5
+ delete(name: string): void;
6
+ get(name: string): FormDataEntryValue | null;
7
+ getAll(name: string): FormDataEntryValue[];
8
+ has(name: string): boolean;
9
+ set(name: string, value: string | Blob, fileName?: string): void;
10
+ forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void;
11
+ entries(): IterableIterator<[string, FormDataEntryValue]>;
12
+ keys(): IterableIterator<string>;
13
+ values(): IterableIterator<FormDataEntryValue>;
14
+ [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
15
+ }