remix-validated-form 1.1.0 → 1.1.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 (50) hide show
  1. package/.eslintcache +1 -1
  2. package/.prettierignore +2 -0
  3. package/README.md +51 -3
  4. package/browser/ValidatedForm.js +1 -1
  5. package/browser/flatten.d.ts +5 -0
  6. package/browser/flatten.js +41 -0
  7. package/browser/hooks.js +5 -1
  8. package/browser/index.d.ts +1 -0
  9. package/browser/index.js +1 -0
  10. package/browser/validation/createValidator.d.ts +3 -0
  11. package/browser/validation/createValidator.js +8 -0
  12. package/browser/validation/types.d.ts +5 -2
  13. package/browser/validation/validation.test.js +92 -8
  14. package/browser/validation/withYup.js +28 -25
  15. package/browser/validation/withZod.js +16 -4
  16. package/build/ValidatedForm.js +1 -1
  17. package/build/flatten.d.ts +5 -0
  18. package/build/flatten.js +49 -0
  19. package/build/hooks.js +8 -1
  20. package/build/index.d.ts +1 -0
  21. package/build/index.js +1 -0
  22. package/build/validation/createValidator.d.ts +3 -0
  23. package/build/validation/createValidator.js +12 -0
  24. package/build/validation/types.d.ts +5 -2
  25. package/build/validation/validation.test.js +92 -8
  26. package/build/validation/withYup.js +28 -25
  27. package/build/validation/withZod.js +19 -4
  28. package/package.json +18 -13
  29. package/sample-app/.env +7 -0
  30. package/sample-app/README.md +53 -0
  31. package/sample-app/app/components/ErrorBox.tsx +34 -0
  32. package/sample-app/app/components/FormInput.tsx +40 -0
  33. package/sample-app/app/components/FormSelect.tsx +37 -0
  34. package/sample-app/app/components/SubjectForm.tsx +150 -0
  35. package/sample-app/app/entry.client.tsx +4 -0
  36. package/sample-app/app/entry.server.tsx +21 -0
  37. package/sample-app/app/root.tsx +92 -0
  38. package/sample-app/app/routes/index.tsx +5 -0
  39. package/sample-app/app/routes/subjects/$id.edit.tsx +100 -0
  40. package/sample-app/app/routes/subjects/index.tsx +112 -0
  41. package/sample-app/app/routes/subjects/new.tsx +48 -0
  42. package/sample-app/app/services/db.server.ts +23 -0
  43. package/sample-app/app/types.ts +6 -0
  44. package/sample-app/package-lock.json +4617 -0
  45. package/sample-app/package.json +36 -0
  46. package/sample-app/prisma/dev.db +0 -0
  47. package/sample-app/prisma/schema.prisma +34 -0
  48. package/sample-app/public/favicon.ico +0 -0
  49. package/sample-app/remix.config.js +10 -0
  50. package/sample-app/remix.env.d.ts +2 -0
package/.eslintcache CHANGED
@@ -1 +1 @@
1
- [{"/Users/aaronpettengill/dev/remix-validated-form/src/server.ts":"1","/Users/aaronpettengill/dev/remix-validated-form/src/validation/types.ts":"2","/Users/aaronpettengill/dev/remix-validated-form/src/validation/withYup.ts":"3","/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx":"4","/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation-fetcher.tsx":"5","/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation-with-fetchers.ts":"6","/Users/aaronpettengill/dev/remix-validated-form/src/validation/validation.test.ts":"7","/Users/aaronpettengill/dev/remix-validated-form/src/validation/withZod.ts":"8"},{"size":207,"mtime":1637876506168,"results":"9","hashOfConfig":"10"},{"size":438,"mtime":1637877226360,"results":"11","hashOfConfig":"10"},{"size":1085,"mtime":1637877476573,"results":"12","hashOfConfig":"10"},{"size":1293,"mtime":1637876566355,"results":"13","hashOfConfig":"10"},{"size":1330,"mtime":1637902697212,"results":"14","hashOfConfig":"10"},{"size":2220,"mtime":1637902736281,"results":"15","hashOfConfig":"10"},{"size":3526,"mtime":1638155421909,"results":"16","hashOfConfig":"10"},{"size":1168,"mtime":1638155747107,"results":"17","hashOfConfig":"10"},{"filePath":"18","messages":"19","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"bt07le",{"filePath":"20","messages":"21","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"22","messages":"23","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"24","messages":"25","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"26","messages":"27","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"28","messages":"29","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"30","messages":"31","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"32","messages":"33","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/aaronpettengill/dev/remix-validated-form/src/server.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/types.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/withYup.ts",["34"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx",[],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation-fetcher.tsx",["35"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation-with-fetchers.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/validation.test.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/withZod.ts",[],{"ruleId":"36","severity":1,"message":"37","line":2,"column":23,"nodeType":"38","messageId":"39","endLine":2,"endColumn":39},{"ruleId":"36","severity":1,"message":"40","line":1,"column":26,"nodeType":"38","messageId":"39","endLine":1,"endColumn":39},"@typescript-eslint/no-unused-vars","'ValidationResult' is defined but never used.","Identifier","unusedVar","'useActionData' is defined but never used."]
1
+ [{"/Users/aaronpettengill/dev/remix-validated-form/src/server.ts":"1","/Users/aaronpettengill/dev/remix-validated-form/src/validation/types.ts":"2","/Users/aaronpettengill/dev/remix-validated-form/src/validation/withYup.ts":"3","/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx":"4","/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation-fetcher.tsx":"5","/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation-with-fetchers.ts":"6","/Users/aaronpettengill/dev/remix-validated-form/src/validation/validation.test.ts":"7","/Users/aaronpettengill/dev/remix-validated-form/src/validation/withZod.ts":"8","/Users/aaronpettengill/dev/remix-validated-form/src/index.ts":"9","/Users/aaronpettengill/dev/remix-validated-form/src/ValidatedForm.tsx":"10"},{"size":207,"mtime":1637876506168,"results":"11","hashOfConfig":"12"},{"size":438,"mtime":1637877226360,"results":"13","hashOfConfig":"12"},{"size":1085,"mtime":1637877476573,"results":"14","hashOfConfig":"12"},{"size":1293,"mtime":1637876566355,"results":"15","hashOfConfig":"12"},{"size":1330,"mtime":1637902697212,"results":"16","hashOfConfig":"12"},{"size":2220,"mtime":1637902736281,"results":"17","hashOfConfig":"12"},{"size":3526,"mtime":1638155421909,"results":"18","hashOfConfig":"12"},{"size":1168,"mtime":1638155747107,"results":"19","hashOfConfig":"12"},{"size":196,"mtime":1638159719317,"results":"20","hashOfConfig":"12"},{"size":3478,"mtime":1638498151067,"results":"21","hashOfConfig":"12"},{"filePath":"22","messages":"23","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"bt07le",{"filePath":"24","messages":"25","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"26","messages":"27","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"28","messages":"29","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"30","messages":"31","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"32","messages":"33","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"34","messages":"35","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"36","messages":"37","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"38","messages":"39","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"40","messages":"41","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/aaronpettengill/dev/remix-validated-form/src/server.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/types.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/withYup.ts",["42"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx",[],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation-fetcher.tsx",["43"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation-with-fetchers.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/validation.test.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/withZod.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/index.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/ValidatedForm.tsx",[],{"ruleId":"44","severity":1,"message":"45","line":2,"column":23,"nodeType":"46","messageId":"47","endLine":2,"endColumn":39},{"ruleId":"44","severity":1,"message":"48","line":1,"column":26,"nodeType":"46","messageId":"47","endLine":1,"endColumn":39},"@typescript-eslint/no-unused-vars","'ValidationResult' is defined but never used.","Identifier","unusedVar","'useActionData' is defined but never used."]
package/.prettierignore CHANGED
@@ -3,6 +3,8 @@ build
3
3
  browser
4
4
  test-app/build
5
5
  test-app/remix-validated-form
6
+ sample-app/build
7
+ sample-app/remix-validated-form
6
8
  node_modules
7
9
  public
8
10
  package-lock.json
package/README.md CHANGED
@@ -7,11 +7,23 @@ A form library built for [remix](https://remix.run) to make validation easy.
7
7
  - Re-use validation on the server
8
8
  - Show validation errors from the server even without JS
9
9
  - Detect if the current form is submitting when there are multiple forms on the page
10
+ - Supports nested objects and arrays
10
11
  - Validation library agnostic
11
12
 
12
13
  # Demo
13
14
 
14
- https://user-images.githubusercontent.com/25882770/143505448-c4b7e660-7a73-4005-b2ca-17c65a15ef46.mov
15
+ https://user-images.githubusercontent.com/2811287/145734901-700a5085-a10b-4d89-88e1-5de9142b1e85.mov
16
+
17
+ To run `sample-app`:
18
+ ```
19
+ git clone https://github.com/airjp73/remix-validated-form
20
+ cd remix-validated-form
21
+ npm i
22
+ cd sample-app
23
+ npm i
24
+ cd ..
25
+ npm run sample-app
26
+ ```
15
27
 
16
28
  # Getting started
17
29
 
@@ -57,7 +69,7 @@ export const MyInput = ({ name, label }: InputProps) => {
57
69
  To best take advantage of the per-form submission detection, we can create a submit button component.
58
70
 
59
71
  ```tsx
60
- import { useIsSubmitting } from "../../remix-validated-form";
72
+ import { useIsSubmitting } from "remix-validated-form";
61
73
 
62
74
  export const MySubmitButton = () => {
63
75
  const isSubmitting = useIsSubmitting();
@@ -127,6 +139,33 @@ export default function MyForm() {
127
139
  }
128
140
  ```
129
141
 
142
+ ## Nested objects and arrays
143
+
144
+ You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
145
+
146
+ ```tsx
147
+ export default function MyForm() {
148
+ const { defaultValues } = useLoaderData();
149
+ return (
150
+ <ValidatedForm
151
+ validator={validator}
152
+ method="post"
153
+ defaultValues={defaultValues}
154
+ >
155
+ <MyInput name="firstName" label="First Name" />
156
+ <MyInput name="lastName" label="Last Name" />
157
+ <MyInput name="address.street" label="Street" />
158
+ <MyInput name="address.city" label="City" />
159
+ <MyInput name="phones[0].type" label="Phone 1 Type" />
160
+ <MyInput name="phones[0].number" label="Phone 1 Number" />
161
+ <MyInput name="phones[1].type" label="Phone 2 Type" />
162
+ <MyInput name="phones[1].number" label="Phone 2 Number" />
163
+ <MySubmitButton />
164
+ </ValidatedForm>
165
+ );
166
+ }
167
+ ```
168
+
130
169
  # Validation Library Support
131
170
 
132
171
  This library currently includes an out-of-the-box adapter for `yup` and `zod`,
@@ -159,13 +198,15 @@ type Validator<DataType> = {
159
198
  In order to make an adapter for your validation library of choice,
160
199
  you can create a function that accepts a schema from the validation library and turns it into a validator.
161
200
 
201
+ Note the use of `createValidator`. It takes care of unflatten the data for nested objects and arrays since the form doesn't know anything about object and arrays and this should be handled by the adapter. For more on this you can check the implementations for `withZod` and `withYup`.
202
+
162
203
  The out-of-the-box support for `yup` in this library works like this:
163
204
 
164
205
  ```ts
165
206
  export const withYup = <Schema extends AnyObjectSchema>(
166
207
  validationSchema: Schema
167
208
  // For best result with Typescript, we should type the `Validator` we return based on the provided schema
168
- ): Validator<InferType<Schema>> => ({
209
+ ): Validator<InferType<Schema>> => createValidator({
169
210
  validate: (unvalidatedData) => {
170
211
  // Validate with yup and return the validated & typed data or the error
171
212
 
@@ -180,3 +221,10 @@ export const withYup = <Schema extends AnyObjectSchema>(
180
221
  },
181
222
  });
182
223
  ```
224
+
225
+ # Frequenty Asked Questions
226
+
227
+ ## Why are my fields triggering the native HTML validations before `remix-validated-form` ones?
228
+ This is happening because you or the library you are using are passing the `required` attribute to the fields. This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors. If you wan't to disable all native HTML validations you can add `noValidate` to `<ValidatedForm>`. We recommend this approach since the validation will still work even if JS is disabled.
229
+
230
+
@@ -21,7 +21,7 @@ const useIsSubmitting = (action, fetcher) => {
21
21
  return fetcher
22
22
  ? fetcher.state === "submitting"
23
23
  : pendingFormSubmit &&
24
- pendingFormSubmit.action.endsWith(action !== null && action !== void 0 ? action : actionForCurrentPage);
24
+ pendingFormSubmit.action === (action !== null && action !== void 0 ? action : actionForCurrentPage);
25
25
  };
26
26
  const getDataFromForm = (el) => Object.fromEntries(new FormData(el));
27
27
  export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
@@ -0,0 +1,5 @@
1
+ import { GenericObject } from ".";
2
+ /** Unflatten a previously flatten object */
3
+ export declare function unflatten(params: GenericObject): {};
4
+ /** Flatten an object so there are no nested objects or arrays */
5
+ export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
@@ -0,0 +1,41 @@
1
+ // `flatten` and `unflatten` are 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 reduce from "lodash/reduce";
8
+ import set from "lodash/set";
9
+ import transform from "lodash/transform";
10
+ /** Unflatten a previously flatten object */
11
+ export function unflatten(params) {
12
+ return reduce(params, function (result, value, key) {
13
+ return set(result, key, value);
14
+ }, {});
15
+ }
16
+ /** Flatten an object so there are no nested objects or arrays */
17
+ export function flatten(obj, preserveEmpty = false) {
18
+ return transform(obj, function (result, value, key) {
19
+ if (isObject(value)) {
20
+ let flatMap = mapKeys(flatten(value, preserveEmpty), function (_mvalue, mkey) {
21
+ if (isArray(value)) {
22
+ let index = mkey.indexOf(".");
23
+ if (-1 !== index) {
24
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
25
+ }
26
+ return `${key}[${mkey}]`;
27
+ }
28
+ return `${key}.${mkey}`;
29
+ });
30
+ assign(result, flatMap);
31
+ // Preverve Empty arrays and objects
32
+ if (preserveEmpty && keys(flatMap).length === 0) {
33
+ result[key] = value;
34
+ }
35
+ }
36
+ else {
37
+ result[key] = value;
38
+ }
39
+ return result;
40
+ }, {});
41
+ }
package/browser/hooks.js CHANGED
@@ -1,3 +1,5 @@
1
+ import get from "lodash/get";
2
+ import toPath from "lodash/toPath";
1
3
  import { useContext, useMemo } from "react";
2
4
  import { FormContext } from "./internal/formContext";
3
5
  export const useField = (name) => {
@@ -8,7 +10,9 @@ export const useField = (name) => {
8
10
  clearError(name);
9
11
  },
10
12
  validate: () => validateField(name),
11
- defaultValue: defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues[name],
13
+ defaultValue: defaultValues
14
+ ? get(defaultValues, toPath(name), undefined)
15
+ : undefined,
12
16
  }), [clearError, defaultValues, fieldErrors, name, validateField]);
13
17
  return field;
14
18
  };
@@ -3,3 +3,4 @@ export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/withYup";
6
+ export * from "./validation/withZod";
package/browser/index.js CHANGED
@@ -3,3 +3,4 @@ export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/withYup";
6
+ export * from "./validation/withZod";
@@ -0,0 +1,3 @@
1
+ import { Validator } from "..";
2
+ /** Handles data manipulation such us flattening the data to send to the validator */
3
+ export declare function createValidator<T>(validator: Validator<T>): Validator<T>;
@@ -0,0 +1,8 @@
1
+ import { unflatten } from "../flatten";
2
+ /** Handles data manipulation such us flattening the data to send to the validator */
3
+ export function createValidator(validator) {
4
+ return {
5
+ validate: (value) => validator.validate(unflatten(value)),
6
+ validateField: (data, field) => validator.validateField(unflatten(data), field),
7
+ };
8
+ }
@@ -1,4 +1,7 @@
1
1
  export declare type FieldErrors = Record<string, string>;
2
+ export declare type GenericObject = {
3
+ [key: string]: any;
4
+ };
2
5
  export declare type ValidationResult<DataType> = {
3
6
  data: DataType;
4
7
  error: undefined;
@@ -10,6 +13,6 @@ export declare type ValidateFieldResult = {
10
13
  error?: string;
11
14
  };
12
15
  export declare type Validator<DataType> = {
13
- validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
14
- validateField: (unvalidatedData: unknown, field: string) => ValidateFieldResult;
16
+ validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
17
+ validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
15
18
  };
@@ -9,6 +9,17 @@ const validationTestCases = [
9
9
  firstName: yup.string().required(),
10
10
  lastName: yup.string().required(),
11
11
  age: yup.number(),
12
+ address: yup
13
+ .object({
14
+ streetAddress: yup.string().required(),
15
+ city: yup.string().required(),
16
+ country: yup.string().required(),
17
+ })
18
+ .required(),
19
+ pets: yup.array().of(yup.object({
20
+ animal: yup.string().required(),
21
+ name: yup.string().required(),
22
+ })),
12
23
  })),
13
24
  },
14
25
  {
@@ -17,6 +28,18 @@ const validationTestCases = [
17
28
  firstName: z.string().nonempty(),
18
29
  lastName: z.string().nonempty(),
19
30
  age: z.optional(z.number()),
31
+ address: z.preprocess((value) => (value == null ? {} : value), z.object({
32
+ streetAddress: z.string().nonempty(),
33
+ city: z.string().nonempty(),
34
+ country: z.string().nonempty(),
35
+ })),
36
+ pets: z
37
+ .object({
38
+ animal: z.string().nonempty(),
39
+ name: z.string().nonempty(),
40
+ })
41
+ .array()
42
+ .optional(),
20
43
  })),
21
44
  },
22
45
  ];
@@ -26,41 +49,102 @@ describe("Validation", () => {
26
49
  describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
27
50
  describe("validate", () => {
28
51
  it("should return the data when valid", () => {
29
- const obj = {
52
+ const person = {
30
53
  firstName: "John",
31
54
  lastName: "Doe",
32
55
  age: 30,
56
+ address: {
57
+ streetAddress: "123 Main St",
58
+ city: "Anytown",
59
+ country: "USA",
60
+ },
61
+ pets: [{ animal: "dog", name: "Fido" }],
33
62
  };
34
- expect(validator.validate(obj)).toEqual({
35
- data: obj,
63
+ expect(validator.validate(person)).toEqual({
64
+ data: person,
36
65
  error: undefined,
37
66
  });
38
67
  });
39
68
  it("should return field errors when invalid", () => {
40
- const obj = { age: "hi!" };
69
+ const obj = { age: "hi!", pets: [{ animal: "dog" }] };
41
70
  expect(validator.validate(obj)).toEqual({
42
71
  data: undefined,
43
72
  error: {
44
73
  firstName: anyString,
45
74
  lastName: anyString,
46
75
  age: anyString,
76
+ "address.city": anyString,
77
+ "address.country": anyString,
78
+ "address.streetAddress": anyString,
79
+ "pets[0].name": anyString,
47
80
  },
48
81
  });
49
82
  });
50
83
  });
51
84
  describe("validateField", () => {
52
85
  it("should not return an error if field is valid", () => {
53
- const obj = {
86
+ const person = {
54
87
  firstName: "John",
55
88
  lastName: {}, // invalid, but we should only be validating firstName
56
89
  };
57
- expect(validator.validateField(obj, "firstName")).toEqual({
90
+ expect(validator.validateField(person, "firstName")).toEqual({
91
+ error: undefined,
92
+ });
93
+ });
94
+ it("should not return an error if a nested field is valid", () => {
95
+ const person = {
96
+ firstName: "John",
97
+ lastName: {},
98
+ address: {
99
+ streetAddress: "123 Main St",
100
+ city: "Anytown",
101
+ country: "USA",
102
+ },
103
+ pets: [{ animal: "dog", name: "Fido" }],
104
+ };
105
+ expect(validator.validateField(person, "address.streetAddress")).toEqual({
106
+ error: undefined,
107
+ });
108
+ expect(validator.validateField(person, "address.city")).toEqual({
109
+ error: undefined,
110
+ });
111
+ expect(validator.validateField(person, "address.country")).toEqual({
112
+ error: undefined,
113
+ });
114
+ expect(validator.validateField(person, "pets[0].animal")).toEqual({
115
+ error: undefined,
116
+ });
117
+ expect(validator.validateField(person, "pets[0].name")).toEqual({
58
118
  error: undefined,
59
119
  });
60
120
  });
61
121
  it("should return an error if field is invalid", () => {
62
- const obj = { firstName: "John", lastName: {} };
63
- expect(validator.validateField(obj, "lastName")).toEqual({
122
+ const person = {
123
+ firstName: "John",
124
+ lastName: {},
125
+ address: {
126
+ streetAddress: "123 Main St",
127
+ city: 1234,
128
+ },
129
+ };
130
+ expect(validator.validateField(person, "lastName")).toEqual({
131
+ error: anyString,
132
+ });
133
+ });
134
+ it("should return an error if a nested field is invalid", () => {
135
+ const person = {
136
+ firstName: "John",
137
+ lastName: {},
138
+ address: {
139
+ streetAddress: "123 Main St",
140
+ city: 1234,
141
+ },
142
+ pets: [{ animal: "dog" }],
143
+ };
144
+ expect(validator.validateField(person, "address.country")).toEqual({
145
+ error: anyString,
146
+ });
147
+ expect(validator.validateField(person, "pets[0].name")).toEqual({
64
148
  error: anyString,
65
149
  });
66
150
  });
@@ -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,30 @@ 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
+ export const withYup = (validationSchema) => {
12
+ return createValidator({
13
+ validate: (data) => {
14
+ try {
15
+ const validated = validationSchema.validateSync(data, {
16
+ abortEarly: false,
17
+ });
18
+ return { data: validated, error: undefined };
19
+ }
20
+ catch (err) {
21
+ return {
22
+ error: validationErrorToFieldErrors(err),
23
+ data: undefined,
24
+ };
25
+ }
26
+ },
27
+ validateField: (data, field) => {
28
+ try {
29
+ validationSchema.validateSyncAt(field, data);
30
+ return {};
31
+ }
32
+ catch (err) {
33
+ return { error: err.message };
34
+ }
35
+ },
36
+ });
37
+ };
@@ -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,21 @@ 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
+ }
11
20
  export function withZod(zodSchema) {
12
- return {
21
+ return createValidator({
13
22
  validate: (value) => {
14
23
  const result = zodSchema.safeParse(value);
15
24
  if (result.success)
16
25
  return { data: result.data, error: undefined };
17
26
  const fieldErrors = {};
18
27
  getIssuesForError(result.error).forEach((issue) => {
19
- const path = issue.path.join(".");
28
+ const path = pathToString(issue.path);
20
29
  if (!fieldErrors[path])
21
30
  fieldErrors[path] = issue.message;
22
31
  });
@@ -28,8 +37,11 @@ export function withZod(zodSchema) {
28
37
  if (result.success)
29
38
  return { error: undefined };
30
39
  return {
31
- error: (_a = getIssuesForError(result.error).find((issue) => issue.path.join(".") === field)) === null || _a === void 0 ? void 0 : _a.message,
40
+ error: (_a = getIssuesForError(result.error).find((issue) => {
41
+ const allPathsAsString = issue.path.map((p) => `${p}`);
42
+ return isEqual(allPathsAsString, toPath(field));
43
+ })) === null || _a === void 0 ? void 0 : _a.message,
32
44
  };
33
45
  },
34
- };
46
+ });
35
47
  }
@@ -27,7 +27,7 @@ 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
32
  const getDataFromForm = (el) => Object.fromEntries(new FormData(el));
33
33
  function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
@@ -0,0 +1,5 @@
1
+ import { GenericObject } from ".";
2
+ /** Unflatten a previously flatten object */
3
+ export declare function unflatten(params: GenericObject): {};
4
+ /** Flatten an object so there are no nested objects or arrays */
5
+ export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
@@ -0,0 +1,49 @@
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.unflatten = void 0;
7
+ // `flatten` and `unflatten` are 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 reduce_1 = __importDefault(require("lodash/reduce"));
14
+ const set_1 = __importDefault(require("lodash/set"));
15
+ const transform_1 = __importDefault(require("lodash/transform"));
16
+ /** Unflatten a previously flatten object */
17
+ function unflatten(params) {
18
+ return (0, reduce_1.default)(params, function (result, value, key) {
19
+ return (0, set_1.default)(result, key, value);
20
+ }, {});
21
+ }
22
+ exports.unflatten = unflatten;
23
+ /** Flatten an object so there are no nested objects or arrays */
24
+ function flatten(obj, preserveEmpty = false) {
25
+ return (0, transform_1.default)(obj, function (result, value, key) {
26
+ if ((0, isObject_1.default)(value)) {
27
+ let flatMap = (0, mapKeys_1.default)(flatten(value, preserveEmpty), function (_mvalue, mkey) {
28
+ if ((0, isArray_1.default)(value)) {
29
+ let index = mkey.indexOf(".");
30
+ if (-1 !== index) {
31
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
32
+ }
33
+ return `${key}[${mkey}]`;
34
+ }
35
+ return `${key}.${mkey}`;
36
+ });
37
+ (0, assign_1.default)(result, flatMap);
38
+ // Preverve Empty arrays and objects
39
+ if (preserveEmpty && (0, keys_1.default)(flatMap).length === 0) {
40
+ result[key] = value;
41
+ }
42
+ }
43
+ else {
44
+ result[key] = value;
45
+ }
46
+ return result;
47
+ }, {});
48
+ }
49
+ exports.flatten = flatten;
package/build/hooks.js CHANGED
@@ -1,6 +1,11 @@
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");
6
11
  const useField = (name) => {
@@ -11,7 +16,9 @@ const useField = (name) => {
11
16
  clearError(name);
12
17
  },
13
18
  validate: () => validateField(name),
14
- defaultValue: defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues[name],
19
+ defaultValue: defaultValues
20
+ ? (0, get_1.default)(defaultValues, (0, toPath_1.default)(name), undefined)
21
+ : undefined,
15
22
  }), [clearError, defaultValues, fieldErrors, name, validateField]);
16
23
  return field;
17
24
  };
package/build/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/withYup";
6
+ export * from "./validation/withZod";
package/build/index.js CHANGED
@@ -15,3 +15,4 @@ __exportStar(require("./server"), exports);
15
15
  __exportStar(require("./ValidatedForm"), exports);
16
16
  __exportStar(require("./validation/types"), exports);
17
17
  __exportStar(require("./validation/withYup"), exports);
18
+ __exportStar(require("./validation/withZod"), exports);
@@ -0,0 +1,3 @@
1
+ import { Validator } from "..";
2
+ /** Handles data manipulation such us flattening the data to send to the validator */
3
+ export declare function createValidator<T>(validator: Validator<T>): Validator<T>;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createValidator = void 0;
4
+ const flatten_1 = require("../flatten");
5
+ /** Handles data manipulation such us flattening the data to send to the validator */
6
+ function createValidator(validator) {
7
+ return {
8
+ validate: (value) => validator.validate((0, flatten_1.unflatten)(value)),
9
+ validateField: (data, field) => validator.validateField((0, flatten_1.unflatten)(data), field),
10
+ };
11
+ }
12
+ exports.createValidator = createValidator;
@@ -1,4 +1,7 @@
1
1
  export declare type FieldErrors = Record<string, string>;
2
+ export declare type GenericObject = {
3
+ [key: string]: any;
4
+ };
2
5
  export declare type ValidationResult<DataType> = {
3
6
  data: DataType;
4
7
  error: undefined;
@@ -10,6 +13,6 @@ export declare type ValidateFieldResult = {
10
13
  error?: string;
11
14
  };
12
15
  export declare type Validator<DataType> = {
13
- validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
14
- validateField: (unvalidatedData: unknown, field: string) => ValidateFieldResult;
16
+ validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
17
+ validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
15
18
  };