remix-validated-form 0.0.4 → 1.1.1-beta.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 (72) hide show
  1. package/.eslintcache +1 -1
  2. package/.prettierignore +2 -0
  3. package/README.md +76 -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 +2 -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 +221 -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 +6 -0
  26. package/browser/validation/withZod.js +50 -0
  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 +2 -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 +221 -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 +6 -0
  49. package/build/validation/withZod.js +57 -0
  50. package/package.json +20 -14
  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
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"},{"size":207,"mtime":1637876506168,"results":"5","hashOfConfig":"6"},{"size":438,"mtime":1637877226360,"results":"7","hashOfConfig":"6"},{"size":1085,"mtime":1637877476573,"results":"8","hashOfConfig":"6"},{"size":1293,"mtime":1637876566355,"results":"9","hashOfConfig":"6"},{"filePath":"10","messages":"11","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"bt07le",{"filePath":"12","messages":"13","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"14","messages":"15","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"16","messages":"17","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",["18"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx",[],{"ruleId":"19","severity":1,"message":"20","line":2,"column":23,"nodeType":"21","messageId":"22","endLine":2,"endColumn":39},"@typescript-eslint/no-unused-vars","'ValidationResult' is defined but never used.","Identifier","unusedVar"]
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","/Users/aaronpettengill/dev/remix-validated-form/src/test-data/testFormData.ts":"11","/Users/aaronpettengill/dev/remix-validated-form/src/validation/createValidator.ts":"12","/Users/aaronpettengill/dev/remix-validated-form/sample-app/app/routes/subjects/$id.edit.tsx":"13","/Users/aaronpettengill/dev/remix-validated-form/sample-app/app/routes/subjects/new.tsx":"14","/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation.ts":"15","/Users/aaronpettengill/dev/remix-validated-form/src/internal/flatten.ts":"16","/Users/aaronpettengill/dev/remix-validated-form/src/hooks.ts":"17","/Users/aaronpettengill/dev/remix-validated-form/src/internal/formContext.ts":"18"},{"size":397,"mtime":1639369089430,"results":"19","hashOfConfig":"20"},{"size":703,"mtime":1639369496819,"results":"21","hashOfConfig":"20"},{"size":1247,"mtime":1639369392705,"results":"22","hashOfConfig":"20"},{"size":1491,"mtime":1639368189315,"results":"23","hashOfConfig":"20"},{"size":1287,"mtime":1639367237366,"results":"24","hashOfConfig":"20"},{"size":2220,"mtime":1637902736281,"results":"25","hashOfConfig":"26"},{"size":8822,"mtime":1639367825741,"results":"27","hashOfConfig":"20"},{"size":1712,"mtime":1639369411474,"results":"28","hashOfConfig":"20"},{"size":242,"mtime":1639368587278,"results":"29","hashOfConfig":"20"},{"size":4105,"mtime":1639369052724,"results":"30","hashOfConfig":"20"},{"size":1639,"mtime":1639366476728,"results":"31","hashOfConfig":"20"},{"size":975,"mtime":1639369381723,"results":"32","hashOfConfig":"20"},{"size":2458,"mtime":1639367225263,"results":"33","hashOfConfig":"20"},{"size":1199,"mtime":1639367241997,"results":"34","hashOfConfig":"20"},{"size":3541,"mtime":1639368136413,"results":"35","hashOfConfig":"20"},{"size":1638,"mtime":1639368636134,"results":"36","hashOfConfig":"20"},{"size":1605,"mtime":1639369330598,"results":"37","hashOfConfig":"20"},{"size":818,"mtime":1639369884523,"results":"38","hashOfConfig":"20"},{"filePath":"39","messages":"40","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1p84lfm",{"filePath":"41","messages":"42","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"43","messages":"44","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"45","messages":"46","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"47","messages":"48","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"49","messages":"50","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"bt07le",{"filePath":"51","messages":"52","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"53","messages":"54","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"55","messages":"56","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"57","messages":"58","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"59","messages":"60","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"61","messages":"62","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"63","messages":"64","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"65","messages":"66","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"67","messages":"68","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"69","messages":"70","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"71","messages":"72","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"73","messages":"74","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",[],"/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",[],"/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",[],"/Users/aaronpettengill/dev/remix-validated-form/src/test-data/testFormData.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/createValidator.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/sample-app/app/routes/subjects/$id.edit.tsx",[],"/Users/aaronpettengill/dev/remix-validated-form/sample-app/app/routes/subjects/new.tsx",[],"/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/internal/flatten.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/hooks.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/internal/formContext.ts",[]]
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,8 +7,25 @@ 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
 
13
+ # Demo
14
+
15
+ https://user-images.githubusercontent.com/2811287/145734901-700a5085-a10b-4d89-88e1-5de9142b1e85.mov
16
+
17
+ To run `sample-app`:
18
+
19
+ ```
20
+ git clone https://github.com/airjp73/remix-validated-form
21
+ cd remix-validated-form
22
+ npm i
23
+ cd sample-app
24
+ npm i
25
+ cd ..
26
+ npm run sample-app
27
+ ```
28
+
12
29
  # Getting started
13
30
 
14
31
  ## Install
@@ -53,7 +70,7 @@ export const MyInput = ({ name, label }: InputProps) => {
53
70
  To best take advantage of the per-form submission detection, we can create a submit button component.
54
71
 
55
72
  ```tsx
56
- import { useIsSubmitting } from "../../remix-validated-form";
73
+ import { useIsSubmitting } from "remix-validated-form";
57
74
 
58
75
  export const MySubmitButton = () => {
59
76
  const isSubmitting = useIsSubmitting();
@@ -85,9 +102,7 @@ const validator = withYup(
85
102
  );
86
103
 
87
104
  export const action: ActionFunction = async ({ request }) => {
88
- const fieldValues = validator.validate(
89
- Object.fromEntries(await request.formData())
90
- );
105
+ const fieldValues = validator.validate(await request.formData());
91
106
  if (fieldValues.error) return validationError(fieldValues.error);
92
107
  const { firstName, lastName, email } = fieldValues.data;
93
108
 
@@ -123,9 +138,36 @@ export default function MyForm() {
123
138
  }
124
139
  ```
125
140
 
141
+ ## Nested objects and arrays
142
+
143
+ You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
144
+
145
+ ```tsx
146
+ export default function MyForm() {
147
+ const { defaultValues } = useLoaderData();
148
+ return (
149
+ <ValidatedForm
150
+ validator={validator}
151
+ method="post"
152
+ defaultValues={defaultValues}
153
+ >
154
+ <MyInput name="firstName" label="First Name" />
155
+ <MyInput name="lastName" label="Last Name" />
156
+ <MyInput name="address.street" label="Street" />
157
+ <MyInput name="address.city" label="City" />
158
+ <MyInput name="phones[0].type" label="Phone 1 Type" />
159
+ <MyInput name="phones[0].number" label="Phone 1 Number" />
160
+ <MyInput name="phones[1].type" label="Phone 2 Type" />
161
+ <MyInput name="phones[1].number" label="Phone 2 Number" />
162
+ <MySubmitButton />
163
+ </ValidatedForm>
164
+ );
165
+ }
166
+ ```
167
+
126
168
  # Validation Library Support
127
169
 
128
- This lbirary currently includes an out-of-the-box adapter for `yup`,
170
+ This library currently includes an out-of-the-box adapter for `yup` and `zod`,
129
171
  but you can easily support whatever library you want by creating your own adapter.
130
172
 
131
173
  And if you create an adapter for a library, feel free to make a PR on this library to add official support 😊
@@ -155,24 +197,39 @@ type Validator<DataType> = {
155
197
  In order to make an adapter for your validation library of choice,
156
198
  you can create a function that accepts a schema from the validation library and turns it into a validator.
157
199
 
200
+ Note the use of `createValidator`.
201
+ It takes care of unflattening the data for nested objects and arrays
202
+ since the form doesn't know anything about object and arrays and this should be handled by the adapter.
203
+ For more on this you can check the implementations for `withZod` and `withYup`.
204
+
158
205
  The out-of-the-box support for `yup` in this library works like this:
159
206
 
160
207
  ```ts
161
208
  export const withYup = <Schema extends AnyObjectSchema>(
162
209
  validationSchema: Schema
163
210
  // For best result with Typescript, we should type the `Validator` we return based on the provided schema
164
- ): Validator<InferType<Schema>> => ({
165
- validate: (unvalidatedData) => {
166
- // Validate with yup and return the validated & typed data or the error
167
-
168
- if (isValid) return { data: { field1: "someValue" }, error: undefined };
169
- else return { error: { field1: "Some error!" }, data: undefined };
170
- },
171
- validateField: (unvalidatedData, field) => {
172
- // Validate the specific field with yup
173
-
174
- if (isValid) return { error: undefined };
175
- else return { error: "Some error" };
176
- },
177
- });
211
+ ): Validator<InferType<Schema>> =>
212
+ createValidator({
213
+ validate: (unvalidatedData) => {
214
+ // Validate with yup and return the validated & typed data or the error
215
+
216
+ if (isValid) return { data: { field1: "someValue" }, error: undefined };
217
+ else return { error: { field1: "Some error!" }, data: undefined };
218
+ },
219
+ validateField: (unvalidatedData, field) => {
220
+ // Validate the specific field with yup
221
+
222
+ if (isValid) return { error: undefined };
223
+ else return { error: "Some error" };
224
+ },
225
+ });
178
226
  ```
227
+
228
+ # Frequenty Asked Questions
229
+
230
+ ## Why are my fields triggering the native HTML validations before `remix-validated-form` ones?
231
+
232
+ This is happening because you or the library you are using is passing the `required` attribute to the fields.
233
+ This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors.
234
+ If you wan't to disable all native HTML validations you can add `noValidate` to `<ValidatedForm>`.
235
+ We recommend this approach since the validation will still work even if JS is disabled.
@@ -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;
@@ -21,9 +21,12 @@ 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
- const getDataFromForm = (el) => Object.fromEntries(new FormData(el));
26
+ const getDataFromForm = (el) => new FormData(el);
27
+ /**
28
+ * The primary form component of `remix-validated-form`.
29
+ */
27
30
  export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
28
31
  var _a;
29
32
  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,35 @@
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
+ export const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => set(acc, key, value), {});
10
+ /** Flatten an object so there are no nested objects or arrays */
11
+ export function flatten(obj, preserveEmpty = false) {
12
+ return transform(obj, function (result, value, key) {
13
+ if (isObject(value)) {
14
+ let flatMap = mapKeys(flatten(value, preserveEmpty), function (_mvalue, mkey) {
15
+ if (isArray(value)) {
16
+ let index = mkey.indexOf(".");
17
+ if (-1 !== index) {
18
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
19
+ }
20
+ return `${key}[${mkey}]`;
21
+ }
22
+ return `${key}.${mkey}`;
23
+ });
24
+ assign(result, flatMap);
25
+ // Preverve Empty arrays and objects
26
+ if (preserveEmpty && keys(flatMap).length === 0) {
27
+ result[key] = value;
28
+ }
29
+ }
30
+ else {
31
+ result[key] = value;
32
+ }
33
+ return result;
34
+ }, {});
35
+ }
@@ -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/browser/hooks.js CHANGED
@@ -1,5 +1,10 @@
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";
5
+ /**
6
+ * Provides the data and helpers necessary to set up a field.
7
+ */
3
8
  export const useField = (name) => {
4
9
  const { fieldErrors, clearError, validateField, defaultValues } = useContext(FormContext);
5
10
  const field = useMemo(() => ({
@@ -8,10 +13,20 @@ export const useField = (name) => {
8
13
  clearError(name);
9
14
  },
10
15
  validate: () => validateField(name),
11
- defaultValue: defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues[name],
16
+ defaultValue: defaultValues
17
+ ? get(defaultValues, toPath(name), undefined)
18
+ : undefined,
12
19
  }), [clearError, defaultValues, fieldErrors, name, validateField]);
13
20
  return field;
14
21
  };
15
- // test commit
22
+ /**
23
+ * Provides access to the entire form context.
24
+ * This is not usually necessary, but can be useful for advanced use cases.
25
+ */
16
26
  export const useFormContext = () => useContext(FormContext);
27
+ /**
28
+ * Returns whether or not the parent form is currently being submitted.
29
+ * This is different from remix's `useTransition().submission` in that it
30
+ * is aware of what form it's in and when _that_ form is being submitted.
31
+ */
17
32
  export const useIsSubmitting = () => useFormContext().isSubmitting;
@@ -3,3 +3,5 @@ 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";
7
+ export * from "./validation/createValidator";
package/browser/index.js CHANGED
@@ -3,3 +3,5 @@ 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";
7
+ export * from "./validation/createValidator";
@@ -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,35 @@
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
+ export const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => set(acc, key, value), {});
10
+ /** Flatten an object so there are no nested objects or arrays */
11
+ export function flatten(obj, preserveEmpty = false) {
12
+ return transform(obj, function (result, value, key) {
13
+ if (isObject(value)) {
14
+ let flatMap = mapKeys(flatten(value, preserveEmpty), function (_mvalue, mkey) {
15
+ if (isArray(value)) {
16
+ let index = mkey.indexOf(".");
17
+ if (-1 !== index) {
18
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
19
+ }
20
+ return `${key}[${mkey}]`;
21
+ }
22
+ return `${key}.${mkey}`;
23
+ });
24
+ assign(result, flatMap);
25
+ // Preverve Empty arrays and objects
26
+ if (preserveEmpty && keys(flatMap).length === 0) {
27
+ result[key] = value;
28
+ }
29
+ }
30
+ else {
31
+ result[key] = value;
32
+ }
33
+ return result;
34
+ }, {});
35
+ }
@@ -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
  };
@@ -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/browser/server.js CHANGED
@@ -1,2 +1,7 @@
1
1
  import { json } from "@remix-run/server-runtime";
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 const validationError = (errors) => json({ fieldErrors: errors }, { status: 422 });
@@ -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
+ }
@@ -0,0 +1,46 @@
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 {
4
+ constructor(body) {
5
+ this._params = new URLSearchParams(body);
6
+ }
7
+ append(name, value, fileName) {
8
+ if (typeof value !== "string") {
9
+ throw new Error("formData.append can only accept a string");
10
+ }
11
+ this._params.append(name, value);
12
+ }
13
+ delete(name) {
14
+ this._params.delete(name);
15
+ }
16
+ get(name) {
17
+ return this._params.get(name);
18
+ }
19
+ getAll(name) {
20
+ return this._params.getAll(name);
21
+ }
22
+ has(name) {
23
+ return this._params.has(name);
24
+ }
25
+ set(name, value, fileName) {
26
+ if (typeof value !== "string") {
27
+ throw new Error("formData.set can only accept a string");
28
+ }
29
+ this._params.set(name, value);
30
+ }
31
+ forEach(callbackfn, thisArg) {
32
+ this._params.forEach(callbackfn, thisArg);
33
+ }
34
+ entries() {
35
+ return this._params.entries();
36
+ }
37
+ keys() {
38
+ return this._params.keys();
39
+ }
40
+ values() {
41
+ return this._params.values();
42
+ }
43
+ *[Symbol.iterator]() {
44
+ yield* this._params;
45
+ }
46
+ }
@@ -0,0 +1,7 @@
1
+ import { Validator } from "..";
2
+ /**
3
+ * Used to create a validator for a form.
4
+ * It provides built-in handling for unflattening nested objects and
5
+ * extracting the values from FormData.
6
+ */
7
+ export declare function createValidator<T>(validator: Validator<T>): Validator<T>;
@@ -0,0 +1,19 @@
1
+ import { objectFromPathEntries } from "../internal/flatten";
2
+ const preprocessFormData = (data) => {
3
+ // A slightly janky way of determining if the data is a FormData object
4
+ // since node doesn't really have FormData
5
+ if ("entries" in data && typeof data.entries === "function")
6
+ return objectFromPathEntries([...data.entries()]);
7
+ return objectFromPathEntries(Object.entries(data));
8
+ };
9
+ /**
10
+ * Used to create a validator for a form.
11
+ * It provides built-in handling for unflattening nested objects and
12
+ * extracting the values from FormData.
13
+ */
14
+ export function createValidator(validator) {
15
+ return {
16
+ validate: (value) => validator.validate(preprocessFormData(value)),
17
+ validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
18
+ };
19
+ }
@@ -1,4 +1,10 @@
1
1
  export declare type FieldErrors = Record<string, string>;
2
+ export declare type GenericObject = {
3
+ [key: string]: any;
4
+ };
5
+ /**
6
+ * The result when validating a form.
7
+ */
2
8
  export declare type ValidationResult<DataType> = {
3
9
  data: DataType;
4
10
  error: undefined;
@@ -6,10 +12,16 @@ export declare type ValidationResult<DataType> = {
6
12
  error: FieldErrors;
7
13
  data: undefined;
8
14
  };
15
+ /**
16
+ * The result when validating an individual field in a form.
17
+ */
9
18
  export declare type ValidateFieldResult = {
10
19
  error?: string;
11
20
  };
21
+ /**
22
+ * A `Validator` can be passed to the `validator` prop of a `ValidatedForm`.
23
+ */
12
24
  export declare type Validator<DataType> = {
13
- validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
14
- validateField: (unvalidatedData: unknown, field: string) => ValidateFieldResult;
25
+ validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
26
+ validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
15
27
  };