remix-validated-form 1.1.1-beta.0 → 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 (52) hide show
  1. package/.eslintcache +1 -1
  2. package/README.md +26 -21
  3. package/browser/ValidatedForm.d.ts +22 -0
  4. package/browser/ValidatedForm.js +4 -1
  5. package/browser/flatten.d.ts +1 -2
  6. package/browser/flatten.js +2 -8
  7. package/browser/hooks.d.ts +28 -3
  8. package/browser/hooks.js +12 -1
  9. package/browser/index.d.ts +1 -0
  10. package/browser/index.js +1 -0
  11. package/browser/internal/flatten.d.ts +4 -0
  12. package/browser/internal/flatten.js +35 -0
  13. package/browser/internal/formContext.d.ts +18 -0
  14. package/browser/server.d.ts +5 -0
  15. package/browser/server.js +5 -0
  16. package/browser/test-data/testFormData.d.ts +15 -0
  17. package/browser/test-data/testFormData.js +46 -0
  18. package/browser/validation/createValidator.d.ts +5 -1
  19. package/browser/validation/createValidator.js +15 -4
  20. package/browser/validation/types.d.ts +9 -0
  21. package/browser/validation/validation.test.js +65 -0
  22. package/browser/validation/withYup.d.ts +3 -0
  23. package/browser/validation/withYup.js +3 -0
  24. package/browser/validation/withZod.d.ts +3 -0
  25. package/browser/validation/withZod.js +3 -0
  26. package/build/ValidatedForm.d.ts +22 -0
  27. package/build/ValidatedForm.js +4 -1
  28. package/build/flatten.d.ts +1 -2
  29. package/build/flatten.js +4 -10
  30. package/build/hooks.d.ts +28 -3
  31. package/build/hooks.js +12 -1
  32. package/build/index.d.ts +1 -0
  33. package/build/index.js +1 -0
  34. package/build/internal/flatten.d.ts +4 -0
  35. package/build/internal/flatten.js +43 -0
  36. package/build/internal/formContext.d.ts +18 -0
  37. package/build/server.d.ts +5 -0
  38. package/build/server.js +5 -0
  39. package/build/test-data/testFormData.d.ts +15 -0
  40. package/build/test-data/testFormData.js +50 -0
  41. package/build/validation/createValidator.d.ts +5 -1
  42. package/build/validation/createValidator.js +15 -4
  43. package/build/validation/types.d.ts +9 -0
  44. package/build/validation/validation.test.js +65 -0
  45. package/build/validation/withYup.d.ts +3 -0
  46. package/build/validation/withYup.js +3 -0
  47. package/build/validation/withZod.d.ts +3 -0
  48. package/build/validation/withZod.js +3 -0
  49. package/package.json +1 -1
  50. package/sample-app/app/routes/subjects/$id.edit.tsx +1 -3
  51. package/sample-app/app/routes/subjects/new.tsx +1 -3
  52. package/sample-app/package-lock.json +6292 -19
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","/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."]
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/README.md CHANGED
@@ -15,6 +15,7 @@ A form library built for [remix](https://remix.run) to make validation easy.
15
15
  https://user-images.githubusercontent.com/2811287/145734901-700a5085-a10b-4d89-88e1-5de9142b1e85.mov
16
16
 
17
17
  To run `sample-app`:
18
+
18
19
  ```
19
20
  git clone https://github.com/airjp73/remix-validated-form
20
21
  cd remix-validated-form
@@ -101,9 +102,7 @@ const validator = withYup(
101
102
  );
102
103
 
103
104
  export const action: ActionFunction = async ({ request }) => {
104
- const fieldValues = validator.validate(
105
- Object.fromEntries(await request.formData())
106
- );
105
+ const fieldValues = validator.validate(await request.formData());
107
106
  if (fieldValues.error) return validationError(fieldValues.error);
108
107
  const { firstName, lastName, email } = fieldValues.data;
109
108
 
@@ -141,7 +140,7 @@ export default function MyForm() {
141
140
 
142
141
  ## Nested objects and arrays
143
142
 
144
- You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
143
+ You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
145
144
 
146
145
  ```tsx
147
146
  export default function MyForm() {
@@ -198,7 +197,10 @@ type Validator<DataType> = {
198
197
  In order to make an adapter for your validation library of choice,
199
198
  you can create a function that accepts a schema from the validation library and turns it into a validator.
200
199
 
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`.
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`.
202
204
 
203
205
  The out-of-the-box support for `yup` in this library works like this:
204
206
 
@@ -206,25 +208,28 @@ The out-of-the-box support for `yup` in this library works like this:
206
208
  export const withYup = <Schema extends AnyObjectSchema>(
207
209
  validationSchema: Schema
208
210
  // For best result with Typescript, we should type the `Validator` we return based on the provided schema
209
- ): Validator<InferType<Schema>> => createValidator({
210
- validate: (unvalidatedData) => {
211
- // Validate with yup and return the validated & typed data or the error
212
-
213
- if (isValid) return { data: { field1: "someValue" }, error: undefined };
214
- else return { error: { field1: "Some error!" }, data: undefined };
215
- },
216
- validateField: (unvalidatedData, field) => {
217
- // Validate the specific field with yup
218
-
219
- if (isValid) return { error: undefined };
220
- else return { error: "Some error" };
221
- },
222
- });
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
+ });
223
226
  ```
224
227
 
225
228
  # Frequenty Asked Questions
226
229
 
227
230
  ## 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
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;
@@ -23,7 +23,10 @@ const useIsSubmitting = (action, fetcher) => {
23
23
  : pendingFormSubmit &&
24
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);
@@ -1,5 +1,4 @@
1
1
  import { GenericObject } from ".";
2
- /** Unflatten a previously flatten object */
3
- export declare function unflatten(params: GenericObject): {};
2
+ export declare const objectFromPathEntries: (entries: [string, any][]) => {};
4
3
  /** Flatten an object so there are no nested objects or arrays */
5
4
  export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
@@ -1,18 +1,12 @@
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.
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
2
  import assign from "lodash/assign";
3
3
  import isArray from "lodash/isArray";
4
4
  import isObject from "lodash/isObject";
5
5
  import keys from "lodash/keys";
6
6
  import mapKeys from "lodash/mapKeys";
7
- import reduce from "lodash/reduce";
8
7
  import set from "lodash/set";
9
8
  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
- }
9
+ export const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => set(acc, key, value), {});
16
10
  /** Flatten an object so there are no nested objects or arrays */
17
11
  export function flatten(obj, preserveEmpty = false) {
18
12
  return transform(obj, function (result, value, key) {
@@ -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
@@ -2,6 +2,9 @@ import get from "lodash/get";
2
2
  import toPath from "lodash/toPath";
3
3
  import { useContext, useMemo } from "react";
4
4
  import { FormContext } from "./internal/formContext";
5
+ /**
6
+ * Provides the data and helpers necessary to set up a field.
7
+ */
5
8
  export const useField = (name) => {
6
9
  const { fieldErrors, clearError, validateField, defaultValues } = useContext(FormContext);
7
10
  const field = useMemo(() => ({
@@ -16,6 +19,14 @@ export const useField = (name) => {
16
19
  }), [clearError, defaultValues, fieldErrors, name, validateField]);
17
20
  return field;
18
21
  };
19
- // 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
+ */
20
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
+ */
21
32
  export const useIsSubmitting = () => useFormContext().isSubmitting;
@@ -4,3 +4,4 @@ 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";
package/browser/index.js CHANGED
@@ -4,3 +4,4 @@ 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";
@@ -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
+ }
@@ -1,3 +1,7 @@
1
1
  import { Validator } from "..";
2
- /** Handles data manipulation such us flattening the data to send to the validator */
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
+ */
3
7
  export declare function createValidator<T>(validator: Validator<T>): Validator<T>;
@@ -1,8 +1,19 @@
1
- import { unflatten } from "../flatten";
2
- /** Handles data manipulation such us flattening the data to send to the validator */
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
+ */
3
14
  export function createValidator(validator) {
4
15
  return {
5
- validate: (value) => validator.validate(unflatten(value)),
6
- validateField: (data, field) => validator.validateField(unflatten(data), field),
16
+ validate: (value) => validator.validate(preprocessFormData(value)),
17
+ validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
7
18
  };
8
19
  }
@@ -2,6 +2,9 @@ export declare type FieldErrors = Record<string, string>;
2
2
  export declare type GenericObject = {
3
3
  [key: string]: any;
4
4
  };
5
+ /**
6
+ * The result when validating a form.
7
+ */
5
8
  export declare type ValidationResult<DataType> = {
6
9
  data: DataType;
7
10
  error: undefined;
@@ -9,9 +12,15 @@ export declare type ValidationResult<DataType> = {
9
12
  error: FieldErrors;
10
13
  data: undefined;
11
14
  };
15
+ /**
16
+ * The result when validating an individual field in a form.
17
+ */
12
18
  export declare type ValidateFieldResult = {
13
19
  error?: string;
14
20
  };
21
+ /**
22
+ * A `Validator` can be passed to the `validator` prop of a `ValidatedForm`.
23
+ */
15
24
  export declare type Validator<DataType> = {
16
25
  validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
17
26
  validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
@@ -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
  {
@@ -80,6 +81,70 @@ describe("Validation", () => {
80
81
  },
81
82
  });
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,
122
+ },
123
+ });
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
+ });
83
148
  });
84
149
  describe("validateField", () => {
85
150
  it("should not return an error if field is valid", () => {
@@ -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>>;
@@ -8,6 +8,9 @@ const validationErrorToFieldErrors = (error) => {
8
8
  });
9
9
  return fieldErrors;
10
10
  };
11
+ /**
12
+ * Create a `Validator` using a `yup` schema.
13
+ */
11
14
  export const withYup = (validationSchema) => {
12
15
  return createValidator({
13
16
  validate: (data) => {
@@ -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>;
@@ -17,6 +17,9 @@ function pathToString(array) {
17
17
  return string + (isNaN(Number(item)) ? prefix + item : "[" + item + "]");
18
18
  }, "");
19
19
  }
20
+ /**
21
+ * Create a validator using a `zod` schema.
22
+ */
20
23
  export function withZod(zodSchema) {
21
24
  return createValidator({
22
25
  validate: (value) => {