remix-validated-form 1.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintcache +1 -1
- package/.prettierignore +2 -0
- package/README.md +72 -19
- package/browser/ValidatedForm.d.ts +22 -0
- package/browser/ValidatedForm.js +5 -2
- package/browser/flatten.d.ts +4 -0
- package/browser/flatten.js +35 -0
- package/browser/hooks.d.ts +28 -3
- package/browser/hooks.js +17 -2
- package/browser/index.d.ts +3 -0
- package/browser/index.js +2 -0
- package/browser/internal/flatten.d.ts +4 -0
- package/browser/internal/flatten.js +35 -0
- package/browser/internal/formContext.d.ts +18 -0
- package/browser/server.d.ts +5 -0
- package/browser/server.js +5 -0
- package/browser/test-data/testFormData.d.ts +15 -0
- package/browser/test-data/testFormData.js +46 -0
- package/browser/validation/createValidator.d.ts +7 -0
- package/browser/validation/createValidator.js +19 -0
- package/browser/validation/types.d.ts +14 -2
- package/browser/validation/validation.test.js +157 -8
- package/browser/validation/withYup.d.ts +3 -0
- package/browser/validation/withYup.js +31 -25
- package/browser/validation/withZod.d.ts +3 -0
- package/browser/validation/withZod.js +19 -4
- package/build/ValidatedForm.d.ts +22 -0
- package/build/ValidatedForm.js +5 -2
- package/build/flatten.d.ts +4 -0
- package/build/flatten.js +43 -0
- package/build/hooks.d.ts +28 -3
- package/build/hooks.js +20 -2
- package/build/index.d.ts +3 -0
- package/build/index.js +2 -0
- package/build/internal/flatten.d.ts +4 -0
- package/build/internal/flatten.js +43 -0
- package/build/internal/formContext.d.ts +18 -0
- package/build/server.d.ts +5 -0
- package/build/server.js +5 -0
- package/build/test-data/testFormData.d.ts +15 -0
- package/build/test-data/testFormData.js +50 -0
- package/build/validation/createValidator.d.ts +7 -0
- package/build/validation/createValidator.js +23 -0
- package/build/validation/types.d.ts +14 -2
- package/build/validation/validation.test.js +157 -8
- package/build/validation/withYup.d.ts +3 -0
- package/build/validation/withYup.js +31 -25
- package/build/validation/withZod.d.ts +3 -0
- package/build/validation/withZod.js +22 -4
- package/package.json +18 -13
- package/sample-app/.env +7 -0
- package/sample-app/README.md +53 -0
- package/sample-app/app/components/ErrorBox.tsx +34 -0
- package/sample-app/app/components/FormInput.tsx +40 -0
- package/sample-app/app/components/FormSelect.tsx +37 -0
- package/sample-app/app/components/SubjectForm.tsx +150 -0
- package/sample-app/app/entry.client.tsx +4 -0
- package/sample-app/app/entry.server.tsx +21 -0
- package/sample-app/app/root.tsx +92 -0
- package/sample-app/app/routes/index.tsx +5 -0
- package/sample-app/app/routes/subjects/$id.edit.tsx +98 -0
- package/sample-app/app/routes/subjects/index.tsx +112 -0
- package/sample-app/app/routes/subjects/new.tsx +46 -0
- package/sample-app/app/services/db.server.ts +23 -0
- package/sample-app/app/types.ts +6 -0
- package/sample-app/package-lock.json +10890 -0
- package/sample-app/package.json +36 -0
- package/sample-app/prisma/dev.db +0 -0
- package/sample-app/prisma/schema.prisma +34 -0
- package/sample-app/public/favicon.ico +0 -0
- package/sample-app/remix.config.js +10 -0
- package/sample-app/remix.env.d.ts +2 -0
package/.eslintcache
CHANGED
@@ -1 +1 @@
|
|
1
|
-
[{"/Users/aaronpettengill/dev/remix-validated-form/src/
|
1
|
+
[{"/Users/aaronpettengill/dev/remix-validated-form/src/index.ts":"1"},{"size":306,"mtime":1639405886301,"results":"2","hashOfConfig":"3"},{"filePath":"4","messages":"5","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1p84lfm","/Users/aaronpettengill/dev/remix-validated-form/src/index.ts",[]]
|
package/.prettierignore
CHANGED
package/README.md
CHANGED
@@ -7,11 +7,24 @@ A form library built for [remix](https://remix.run) to make validation easy.
|
|
7
7
|
- Re-use validation on the server
|
8
8
|
- Show validation errors from the server even without JS
|
9
9
|
- Detect if the current form is submitting when there are multiple forms on the page
|
10
|
+
- Supports nested objects and arrays
|
10
11
|
- Validation library agnostic
|
11
12
|
|
12
13
|
# Demo
|
13
14
|
|
14
|
-
https://user-images.githubusercontent.com/
|
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
|
+
```
|
15
28
|
|
16
29
|
# Getting started
|
17
30
|
|
@@ -57,7 +70,7 @@ export const MyInput = ({ name, label }: InputProps) => {
|
|
57
70
|
To best take advantage of the per-form submission detection, we can create a submit button component.
|
58
71
|
|
59
72
|
```tsx
|
60
|
-
import { useIsSubmitting } from "
|
73
|
+
import { useIsSubmitting } from "remix-validated-form";
|
61
74
|
|
62
75
|
export const MySubmitButton = () => {
|
63
76
|
const isSubmitting = useIsSubmitting();
|
@@ -89,9 +102,7 @@ const validator = withYup(
|
|
89
102
|
);
|
90
103
|
|
91
104
|
export const action: ActionFunction = async ({ request }) => {
|
92
|
-
const fieldValues = validator.validate(
|
93
|
-
Object.fromEntries(await request.formData())
|
94
|
-
);
|
105
|
+
const fieldValues = validator.validate(await request.formData());
|
95
106
|
if (fieldValues.error) return validationError(fieldValues.error);
|
96
107
|
const { firstName, lastName, email } = fieldValues.data;
|
97
108
|
|
@@ -127,6 +138,33 @@ export default function MyForm() {
|
|
127
138
|
}
|
128
139
|
```
|
129
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
|
+
|
130
168
|
# Validation Library Support
|
131
169
|
|
132
170
|
This library currently includes an out-of-the-box adapter for `yup` and `zod`,
|
@@ -159,24 +197,39 @@ type Validator<DataType> = {
|
|
159
197
|
In order to make an adapter for your validation library of choice,
|
160
198
|
you can create a function that accepts a schema from the validation library and turns it into a validator.
|
161
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
|
+
|
162
205
|
The out-of-the-box support for `yup` in this library works like this:
|
163
206
|
|
164
207
|
```ts
|
165
208
|
export const withYup = <Schema extends AnyObjectSchema>(
|
166
209
|
validationSchema: Schema
|
167
210
|
// For best result with Typescript, we should type the `Validator` we return based on the provided schema
|
168
|
-
): Validator<InferType<Schema>> =>
|
169
|
-
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
|
179
|
-
|
180
|
-
|
181
|
-
}
|
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
|
+
});
|
182
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;
|
package/browser/ValidatedForm.js
CHANGED
@@ -21,9 +21,12 @@ const useIsSubmitting = (action, fetcher) => {
|
|
21
21
|
return fetcher
|
22
22
|
? fetcher.state === "submitting"
|
23
23
|
: pendingFormSubmit &&
|
24
|
-
pendingFormSubmit.action
|
24
|
+
pendingFormSubmit.action === (action !== null && action !== void 0 ? action : actionForCurrentPage);
|
25
25
|
};
|
26
|
-
const getDataFromForm = (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
|
+
}
|
package/browser/hooks.d.ts
CHANGED
@@ -1,8 +1,33 @@
|
|
1
|
-
export declare
|
2
|
-
|
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
|
-
|
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
|
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
|
-
|
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;
|
package/browser/index.d.ts
CHANGED
@@ -3,3 +3,6 @@ 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";
|
8
|
+
export type { FormContextValue } from "./internal/formContext";
|
package/browser/index.js
CHANGED
@@ -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
|
};
|
package/browser/server.d.ts
CHANGED
@@ -1,2 +1,7 @@
|
|
1
1
|
import { FieldErrors } from "./validation/types";
|
2
|
+
/**
|
3
|
+
* Takes the errors from a `Validator` and returns a `Response`.
|
4
|
+
* The `ValidatedForm` on the frontend will automatically display the errors
|
5
|
+
* if this is returned from the action.
|
6
|
+
*/
|
2
7
|
export declare const validationError: (errors: FieldErrors) => Response;
|
package/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:
|
14
|
-
validateField: (unvalidatedData:
|
25
|
+
validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
|
26
|
+
validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
|
15
27
|
};
|