remix-validated-form 2.0.1-beta.0 → 3.0.0-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.
@@ -1,9 +1,9 @@
1
1
  $ npm run build:browser && npm run build:main
2
2
 
3
- > remix-validated-form@2.0.0 build:browser
3
+ > remix-validated-form@2.1.1 build:browser
4
4
  > tsc --module ESNext --outDir ./browser
5
5
 
6
6
 
7
- > remix-validated-form@2.0.0 build:main
7
+ > remix-validated-form@2.1.1 build:main
8
8
  > tsc --module CommonJS --outDir ./build
9
9
 
@@ -0,0 +1,36 @@
1
+ $ jest src
2
+  PASS  src/validation/validation.test.ts
3
+ Validation
4
+ Adapter for yup
5
+ validate
6
+ ✓ should return the data when valid (2 ms)
7
+ ✓ should return field errors when invalid (1 ms)
8
+ ✓ should unflatten data when validating
9
+ ✓ should accept FormData directly and return errors (1 ms)
10
+ ✓ should accept FormData directly and return valid data (1 ms)
11
+ validateField
12
+ ✓ should not return an error if field is valid
13
+ ✓ should not return an error if a nested field is valid (1 ms)
14
+ ✓ should return an error if field is invalid (2 ms)
15
+ ✓ should return an error if a nested field is invalid
16
+ Adapter for zod
17
+ validate
18
+ ✓ should return the data when valid (1 ms)
19
+ ✓ should return field errors when invalid
20
+ ✓ should unflatten data when validating (1 ms)
21
+ ✓ should accept FormData directly and return errors
22
+ ✓ should accept FormData directly and return valid data
23
+ validateField
24
+ ✓ should not return an error if field is valid (1 ms)
25
+ ✓ should not return an error if a nested field is valid
26
+ ✓ should return an error if field is invalid
27
+ ✓ should return an error if a nested field is invalid
28
+ withZod
29
+ ✓ returns coherent errors for complex schemas (1 ms)
30
+ ✓ returns errors for fields that are unions
31
+
32
+ Test Suites: 1 passed, 1 total
33
+ Tests: 20 passed, 20 total
34
+ Snapshots: 0 total
35
+ Time: 1.1 s, estimated 2 s
36
+ Ran all test suites matching /src/i.
package/README.md ADDED
@@ -0,0 +1,232 @@
1
+ # Remix Validated Form
2
+
3
+ A form library built for [remix](https://remix.run) to make validation easy.
4
+
5
+ - Client-side, field-by-field validation (e.g. validate on blur) and form-level validation
6
+ - Set default values for the entire form in one place
7
+ - Re-use validation on the server
8
+ - Show validation errors from the server even without JS
9
+ - Detect if the current form is submitting when there are multiple forms on the page
10
+ - Supports nested objects and arrays
11
+ - Validation library agnostic
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
+ yarn install
23
+ yarn sample-app
24
+ ```
25
+
26
+ # Getting started
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ npm install remix-validated-form
32
+ ```
33
+
34
+ ## Create an input component
35
+
36
+ In order to display field errors or do field-by-field validation,
37
+ it's recommended to incorporate this library into an input component using `useField`.
38
+
39
+ ```tsx
40
+ import { useField } from "remix-validated-form";
41
+
42
+ type MyInputProps = {
43
+ name: string;
44
+ label: string;
45
+ };
46
+
47
+ export const MyInput = ({ name, label }: InputProps) => {
48
+ const { validate, clearError, defaultValue, error } = useField(name);
49
+ return (
50
+ <div>
51
+ <label htmlFor={name}>{label}</label>
52
+ <input
53
+ id={name}
54
+ name={name}
55
+ onBlur={validate}
56
+ onChange={clearError}
57
+ defaultValue={defaultValue}
58
+ />
59
+ {error && <span className="my-error-class">{error}</span>}
60
+ </div>
61
+ );
62
+ };
63
+ ```
64
+
65
+ ## Create a submit button component
66
+
67
+ To best take advantage of the per-form submission detection, we can create a submit button component.
68
+
69
+ ```tsx
70
+ import { useIsSubmitting } from "remix-validated-form";
71
+
72
+ export const MySubmitButton = () => {
73
+ const isSubmitting = useIsSubmitting();
74
+ return (
75
+ <button type="submit" disabled={isSubmitting}>
76
+ {isSubmitting ? "Submitting..." : "Submit"}
77
+ </button>
78
+ );
79
+ };
80
+ ```
81
+
82
+ ## Use the form!
83
+
84
+ Now that we have our components, making a form is easy!
85
+
86
+ ```tsx
87
+ import { ActionFunction, LoaderFunction, redirect, useLoaderData } from "remix";
88
+ import * as yup from "yup";
89
+ import { validationError, ValidatedForm, withYup } from "remix-validated-form";
90
+ import { MyInput, MySubmitButton } from "~/components/Input";
91
+
92
+ // Using yup in this example, but you can use anything
93
+ const validator = withYup(
94
+ yup.object({
95
+ firstName: yup.string().label("First Name").required(),
96
+ lastName: yup.string().label("Last Name").required(),
97
+ email: yup.string().email().label("Email").required(),
98
+ })
99
+ );
100
+
101
+ export const action: ActionFunction = async ({ request }) => {
102
+ const fieldValues = validator.validate(await request.formData());
103
+ if (fieldValues.error) return validationError(fieldValues.error);
104
+ const { firstName, lastName, email } = fieldValues.data;
105
+
106
+ // Do something with correctly typed values;
107
+
108
+ return redirect("/");
109
+ };
110
+
111
+ export const loader: LoaderFunction = () => {
112
+ return {
113
+ defaultValues: {
114
+ firstName: "Jane",
115
+ lastName: "Doe",
116
+ email: "jane.doe@example.com",
117
+ },
118
+ };
119
+ };
120
+
121
+ export default function MyForm() {
122
+ const { defaultValues } = useLoaderData();
123
+ return (
124
+ <ValidatedForm
125
+ validator={validator}
126
+ method="post"
127
+ defaultValues={defaultValues}
128
+ >
129
+ <MyInput name="firstName" label="First Name" />
130
+ <MyInput name="lastName" label="Last Name" />
131
+ <MyInput name="email" label="Email" />
132
+ <MySubmitButton />
133
+ </ValidatedForm>
134
+ );
135
+ }
136
+ ```
137
+
138
+ ## Nested objects and arrays
139
+
140
+ You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
141
+
142
+ ```tsx
143
+ export default function MyForm() {
144
+ const { defaultValues } = useLoaderData();
145
+ return (
146
+ <ValidatedForm
147
+ validator={validator}
148
+ method="post"
149
+ defaultValues={defaultValues}
150
+ >
151
+ <MyInput name="firstName" label="First Name" />
152
+ <MyInput name="lastName" label="Last Name" />
153
+ <MyInput name="address.street" label="Street" />
154
+ <MyInput name="address.city" label="City" />
155
+ <MyInput name="phones[0].type" label="Phone 1 Type" />
156
+ <MyInput name="phones[0].number" label="Phone 1 Number" />
157
+ <MyInput name="phones[1].type" label="Phone 2 Type" />
158
+ <MyInput name="phones[1].number" label="Phone 2 Number" />
159
+ <MySubmitButton />
160
+ </ValidatedForm>
161
+ );
162
+ }
163
+ ```
164
+
165
+ # Validation Library Support
166
+
167
+ This library currently includes an out-of-the-box adapter for `yup` and `zod`,
168
+ but you can easily support whatever library you want by creating your own adapter.
169
+
170
+ And if you create an adapter for a library, feel free to make a PR on this library to add official support 😊
171
+
172
+ ## Creating an adapter
173
+
174
+ Any object that conforms to the `Validator` type can be passed into the the `ValidatedForm`'s `validator` prop.
175
+
176
+ ```ts
177
+ type FieldErrors = Record<string, string>;
178
+
179
+ type ValidationResult<DataType> =
180
+ | { data: DataType; error: undefined }
181
+ | { error: FieldErrors; data: undefined };
182
+
183
+ type ValidateFieldResult = { error?: string };
184
+
185
+ type Validator<DataType> = {
186
+ validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
187
+ validateField: (
188
+ unvalidatedData: unknown,
189
+ field: string
190
+ ) => ValidateFieldResult;
191
+ };
192
+ ```
193
+
194
+ In order to make an adapter for your validation library of choice,
195
+ you can create a function that accepts a schema from the validation library and turns it into a validator.
196
+
197
+ Note the use of `createValidator`.
198
+ It takes care of unflattening the data for nested objects and arrays
199
+ since the form doesn't know anything about object and arrays and this should be handled by the adapter.
200
+ For more on this you can check the implementations for `withZod` and `withYup`.
201
+
202
+ The out-of-the-box support for `yup` in this library works like this:
203
+
204
+ ```ts
205
+ export const withYup = <Schema extends AnyObjectSchema>(
206
+ validationSchema: Schema
207
+ // For best result with Typescript, we should type the `Validator` we return based on the provided schema
208
+ ): Validator<InferType<Schema>> =>
209
+ 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
+ });
223
+ ```
224
+
225
+ # Frequenty Asked Questions
226
+
227
+ ## Why are my fields triggering the native HTML validations before `remix-validated-form` ones?
228
+
229
+ This is happening because you or the library you are using is passing the `required` attribute to the fields.
230
+ This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors.
231
+ If you wan't to disable all native HTML validations you can add `noValidate` to `<ValidatedForm>`.
232
+ We recommend this approach since the validation will still work even if JS is disabled.
@@ -26,8 +26,20 @@ export declare type FormProps<DataType> = {
26
26
  * A ref to the form element.
27
27
  */
28
28
  formRef?: React.RefObject<HTMLFormElement>;
29
+ /**
30
+ * An optional sub-action to use for the form.
31
+ * Setting a value here will cause the form to be submitted with an extra `subaction` value.
32
+ * This can be useful when there are multiple forms on the screen handled by the same action.
33
+ */
34
+ subaction?: string;
35
+ /**
36
+ * Reset the form to the default values after the form has been successfully submitted.
37
+ * This is useful if you want to submit the same form multiple times,
38
+ * and don't redirect in-between submissions.
39
+ */
40
+ resetAfterSubmit?: boolean;
29
41
  } & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
30
42
  /**
31
43
  * The primary form component of `remix-validated-form`.
32
44
  */
33
- export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }: FormProps<DataType>): JSX.Element;
45
+ export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }: FormProps<DataType>): JSX.Element;
@@ -1,41 +1,89 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Form as RemixForm, useActionData, useFormAction, useTransition, } from "@remix-run/react";
3
3
  import { useEffect, useMemo, useRef, useState, } from "react";
4
4
  import invariant from "tiny-invariant";
5
5
  import { FormContext } from "./internal/formContext";
6
+ import { useSubmitComplete } from "./internal/submissionCallbacks";
6
7
  import { omit, mergeRefs } from "./internal/util";
7
- function useFieldErrors(fetcher) {
8
+ function useFieldErrorsFromBackend(fetcher, subaction) {
9
+ var _a, _b;
8
10
  const actionData = useActionData();
9
- const dataToUse = fetcher ? fetcher.data : actionData;
10
- const fieldErrorsFromAction = dataToUse === null || dataToUse === void 0 ? void 0 : dataToUse.fieldErrors;
11
- const [fieldErrors, setFieldErrors] = useState(fieldErrorsFromAction !== null && fieldErrorsFromAction !== void 0 ? fieldErrorsFromAction : {});
11
+ if (fetcher)
12
+ return (_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors;
13
+ if (!actionData)
14
+ return null;
15
+ if (actionData.fieldErrors) {
16
+ const submittedData = (_b = actionData.fieldErrors) === null || _b === void 0 ? void 0 : _b._submittedData;
17
+ const subactionsMatch = subaction
18
+ ? subaction === (submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction)
19
+ : !(submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction);
20
+ return subactionsMatch ? actionData.fieldErrors : null;
21
+ }
22
+ return null;
23
+ }
24
+ function useFieldErrors(fieldErrorsFromBackend) {
25
+ const [fieldErrors, setFieldErrors] = useState(fieldErrorsFromBackend !== null && fieldErrorsFromBackend !== void 0 ? fieldErrorsFromBackend : {});
12
26
  useEffect(() => {
13
- if (fieldErrorsFromAction)
14
- setFieldErrors(fieldErrorsFromAction);
15
- }, [fieldErrorsFromAction]);
27
+ if (fieldErrorsFromBackend)
28
+ setFieldErrors(fieldErrorsFromBackend);
29
+ }, [fieldErrorsFromBackend]);
16
30
  return [fieldErrors, setFieldErrors];
17
31
  }
18
- const useIsSubmitting = (action, fetcher) => {
32
+ const useIsSubmitting = (action, subaction, fetcher) => {
19
33
  const actionForCurrentPage = useFormAction();
20
34
  const pendingFormSubmit = useTransition().submission;
21
- return fetcher
22
- ? fetcher.state === "submitting"
23
- : pendingFormSubmit &&
24
- pendingFormSubmit.action === (action !== null && action !== void 0 ? action : actionForCurrentPage);
35
+ if (fetcher)
36
+ return fetcher.state === "submitting";
37
+ if (!pendingFormSubmit)
38
+ return false;
39
+ const { formData, action: pendingAction } = pendingFormSubmit;
40
+ const pendingSubAction = formData.get("subaction");
41
+ const expectedAction = action !== null && action !== void 0 ? action : actionForCurrentPage;
42
+ if (subaction)
43
+ return expectedAction === pendingAction && subaction === pendingSubAction;
44
+ return expectedAction === pendingAction && !pendingSubAction;
25
45
  };
26
46
  const getDataFromForm = (el) => new FormData(el);
47
+ /**
48
+ * The purpose for this logic is to handle validation errors when javascript is disabled.
49
+ * Normally (without js), when a form is submitted and the action returns the validation errors,
50
+ * the form will be reset. The errors will be displayed on the correct fields,
51
+ * but all the values in the form will be gone. This is not good UX.
52
+ *
53
+ * To get around this, we return the submitted form data from the server,
54
+ * and use those to populate the form via `defaultValues`.
55
+ * This results in a more seamless UX akin to what you would see when js is enabled.
56
+ *
57
+ * One potential downside is that resetting the form will reset the form
58
+ * to the _new_ default values that were returned from the server with the validation errors.
59
+ * However, this case is less of a problem than the janky UX caused by losing the form values.
60
+ * It will only ever be a problem if the form includes a `<button type="reset" />`
61
+ * and only if JS is disabled.
62
+ */
63
+ function useDefaultValues(fieldErrors, defaultValues) {
64
+ const defaultsFromValidationError = fieldErrors === null || fieldErrors === void 0 ? void 0 : fieldErrors._submittedData;
65
+ return defaultsFromValidationError !== null && defaultsFromValidationError !== void 0 ? defaultsFromValidationError : defaultValues;
66
+ }
27
67
  /**
28
68
  * The primary form component of `remix-validated-form`.
29
69
  */
30
- export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
70
+ export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }) {
31
71
  var _a;
32
- const [fieldErrors, setFieldErrors] = useFieldErrors(fetcher);
33
- const isSubmitting = useIsSubmitting(action, fetcher);
72
+ const fieldErrorsFromBackend = useFieldErrorsFromBackend(fetcher, subaction);
73
+ const [fieldErrors, setFieldErrors] = useFieldErrors(fieldErrorsFromBackend);
74
+ const isSubmitting = useIsSubmitting(action, subaction, fetcher);
75
+ const defaultsToUse = useDefaultValues(fieldErrorsFromBackend, defaultValues);
34
76
  const formRef = useRef(null);
77
+ useSubmitComplete(isSubmitting, () => {
78
+ var _a;
79
+ if (!fieldErrorsFromBackend && resetAfterSubmit) {
80
+ (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.reset();
81
+ }
82
+ });
35
83
  const contextValue = useMemo(() => ({
36
84
  fieldErrors,
37
85
  action,
38
- defaultValues,
86
+ defaultValues: defaultsToUse,
39
87
  isSubmitting: isSubmitting !== null && isSubmitting !== void 0 ? isSubmitting : false,
40
88
  clearError: (fieldName) => {
41
89
  setFieldErrors((prev) => omit(prev, fieldName));
@@ -53,7 +101,7 @@ export function ValidatedForm({ validator, onSubmit, children, fetcher, action,
53
101
  }), [
54
102
  fieldErrors,
55
103
  action,
56
- defaultValues,
104
+ defaultsToUse,
57
105
  isSubmitting,
58
106
  setFieldErrors,
59
107
  validator,
@@ -68,5 +116,10 @@ export function ValidatedForm({ validator, onSubmit, children, fetcher, action,
68
116
  else {
69
117
  onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, event);
70
118
  }
71
- }, children: _jsx(FormContext.Provider, { value: contextValue, children: children }, void 0) }, void 0));
119
+ }, onReset: (event) => {
120
+ onReset === null || onReset === void 0 ? void 0 : onReset(event);
121
+ if (event.defaultPrevented)
122
+ return;
123
+ setFieldErrors({});
124
+ }, children: _jsxs(FormContext.Provider, { value: contextValue, children: [subaction && (_jsx("input", { type: "hidden", value: subaction, name: "subaction" }, void 0)), children] }, void 0) }, void 0));
72
125
  }
@@ -2,7 +2,5 @@ export * from "./hooks";
2
2
  export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
- export * from "./validation/withYup";
6
- export * from "./validation/withZod";
7
5
  export * from "./validation/createValidator";
8
6
  export type { FormContextValue } from "./internal/formContext";
package/browser/index.js CHANGED
@@ -2,6 +2,4 @@ export * from "./hooks";
2
2
  export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
- export * from "./validation/withYup";
6
- export * from "./validation/withZod";
7
5
  export * from "./validation/createValidator";
@@ -0,0 +1 @@
1
+ export declare function useSubmitComplete(isSubmitting: boolean, callback: () => void): void;
@@ -0,0 +1,13 @@
1
+ import { useEffect, useRef } from "react";
2
+ export function useSubmitComplete(isSubmitting, callback) {
3
+ const isPending = useRef(false);
4
+ useEffect(() => {
5
+ if (isSubmitting) {
6
+ isPending.current = true;
7
+ }
8
+ if (!isSubmitting && isPending.current) {
9
+ isPending.current = false;
10
+ callback();
11
+ }
12
+ });
13
+ }
@@ -13,7 +13,18 @@ const preprocessFormData = (data) => {
13
13
  */
14
14
  export function createValidator(validator) {
15
15
  return {
16
- validate: (value) => validator.validate(preprocessFormData(value)),
16
+ validate: (value) => {
17
+ const data = preprocessFormData(value);
18
+ const result = validator.validate(data);
19
+ if (result.error) {
20
+ // Ideally, we should probably be returning a nested object like
21
+ // { fieldErrors: {}, submittedData: {} }
22
+ // We should do this in the next major version of the library
23
+ // but for now, we can sneak it in with the fieldErrors.
24
+ result.error._submittedData = data;
25
+ }
26
+ return result;
27
+ },
17
28
  validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
18
29
  };
19
30
  }
@@ -1,4 +1,7 @@
1
1
  export declare type FieldErrors = Record<string, string>;
2
+ export declare type FieldErrorsWithData = FieldErrors & {
3
+ _submittedData: any;
4
+ };
2
5
  export declare type GenericObject = {
3
6
  [key: string]: any;
4
7
  };
@@ -1,6 +1,7 @@
1
1
  import * as yup from "yup";
2
2
  import { z } from "zod";
3
3
  import { withYup } from "..";
4
+ import { objectFromPathEntries } from "../internal/flatten";
4
5
  import { TestFormData } from "../test-data/testFormData";
5
6
  import { withZod } from "./withZod";
6
7
  const validationTestCases = [
@@ -78,6 +79,7 @@ describe("Validation", () => {
78
79
  "address.country": anyString,
79
80
  "address.streetAddress": anyString,
80
81
  "pets[0].name": anyString,
82
+ _submittedData: obj,
81
83
  },
82
84
  });
83
85
  });
@@ -119,6 +121,7 @@ describe("Validation", () => {
119
121
  error: {
120
122
  "address.city": anyString,
121
123
  "pets[0].name": anyString,
124
+ _submittedData: objectFromPathEntries([...formData.entries()]),
122
125
  },
123
126
  });
124
127
  });
@@ -239,6 +242,7 @@ describe("withZod", () => {
239
242
  type: anyString,
240
243
  bar: anyString,
241
244
  foo: anyString,
245
+ _submittedData: obj,
242
246
  },
243
247
  });
244
248
  });
@@ -257,6 +261,7 @@ describe("withZod", () => {
257
261
  error: {
258
262
  field1: anyString,
259
263
  field2: anyString,
264
+ _submittedData: obj,
260
265
  },
261
266
  });
262
267
  expect(validator.validateField(obj, "field1")).toEqual({
@@ -26,8 +26,20 @@ export declare type FormProps<DataType> = {
26
26
  * A ref to the form element.
27
27
  */
28
28
  formRef?: React.RefObject<HTMLFormElement>;
29
+ /**
30
+ * An optional sub-action to use for the form.
31
+ * Setting a value here will cause the form to be submitted with an extra `subaction` value.
32
+ * This can be useful when there are multiple forms on the screen handled by the same action.
33
+ */
34
+ subaction?: string;
35
+ /**
36
+ * Reset the form to the default values after the form has been successfully submitted.
37
+ * This is useful if you want to submit the same form multiple times,
38
+ * and don't redirect in-between submissions.
39
+ */
40
+ resetAfterSubmit?: boolean;
29
41
  } & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
30
42
  /**
31
43
  * The primary form component of `remix-validated-form`.
32
44
  */
33
- export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }: FormProps<DataType>): JSX.Element;
45
+ export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }: FormProps<DataType>): JSX.Element;