remix-validated-form 1.1.1 → 2.0.0-beta.2
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/.turbo/turbo-build.log +9 -0
- package/.turbo/turbo-dev.log +78 -0
- package/.turbo/turbo-test.log +36 -0
- package/README.md +72 -19
- package/browser/ValidatedForm.d.ts +35 -1
- package/browser/ValidatedForm.js +76 -20
- package/browser/hooks.d.ts +28 -3
- package/browser/hooks.js +17 -2
- package/browser/index.d.ts +2 -0
- package/browser/index.js +1 -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/internal/formContext.js +0 -0
- package/browser/internal/submissionCallbacks.d.ts +1 -0
- package/browser/internal/submissionCallbacks.js +13 -0
- package/browser/internal/util.d.ts +0 -0
- package/browser/internal/util.js +0 -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 +30 -0
- package/browser/validation/types.d.ts +17 -2
- package/browser/validation/types.js +0 -0
- package/browser/validation/validation.test.d.ts +0 -0
- package/browser/validation/validation.test.js +162 -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 +35 -1
- package/build/ValidatedForm.js +75 -19
- package/build/hooks.d.ts +28 -3
- package/build/hooks.js +20 -2
- package/build/index.d.ts +2 -0
- package/build/index.js +1 -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/internal/formContext.js +0 -0
- package/build/internal/submissionCallbacks.d.ts +1 -0
- package/build/internal/submissionCallbacks.js +17 -0
- package/build/internal/util.d.ts +0 -0
- package/build/internal/util.js +0 -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 +34 -0
- package/build/validation/types.d.ts +17 -2
- package/build/validation/types.js +0 -0
- package/build/validation/validation.test.d.ts +0 -0
- package/build/validation/validation.test.js +162 -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/jest.config.js +5 -0
- package/package.json +18 -38
- package/src/ValidatedForm.tsx +227 -0
- package/src/hooks.ts +60 -0
- package/src/index.ts +8 -0
- package/src/internal/flatten.ts +48 -0
- package/src/internal/formContext.ts +36 -0
- package/src/internal/submissionCallbacks.ts +15 -0
- package/src/internal/util.ts +23 -0
- package/src/server.ts +10 -0
- package/src/test-data/testFormData.ts +55 -0
- package/src/validation/createValidator.ts +34 -0
- package/src/validation/types.ts +28 -0
- package/src/validation/validation.test.ts +322 -0
- package/src/validation/withYup.ts +43 -0
- package/src/validation/withZod.ts +51 -0
- package/tsconfig.json +5 -0
- package/.eslintcache +0 -1
- package/.eslintignore +0 -1
- package/.prettierignore +0 -8
- package/LICENSE +0 -21
@@ -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,30 @@
|
|
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) => {
|
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
|
+
},
|
28
|
+
validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
|
29
|
+
};
|
30
|
+
}
|
@@ -1,4 +1,13 @@
|
|
1
1
|
export declare type FieldErrors = Record<string, string>;
|
2
|
+
export declare type FieldErrorsWithData = FieldErrors & {
|
3
|
+
_submittedData: any;
|
4
|
+
};
|
5
|
+
export declare type GenericObject = {
|
6
|
+
[key: string]: any;
|
7
|
+
};
|
8
|
+
/**
|
9
|
+
* The result when validating a form.
|
10
|
+
*/
|
2
11
|
export declare type ValidationResult<DataType> = {
|
3
12
|
data: DataType;
|
4
13
|
error: undefined;
|
@@ -6,10 +15,16 @@ export declare type ValidationResult<DataType> = {
|
|
6
15
|
error: FieldErrors;
|
7
16
|
data: undefined;
|
8
17
|
};
|
18
|
+
/**
|
19
|
+
* The result when validating an individual field in a form.
|
20
|
+
*/
|
9
21
|
export declare type ValidateFieldResult = {
|
10
22
|
error?: string;
|
11
23
|
};
|
24
|
+
/**
|
25
|
+
* A `Validator` can be passed to the `validator` prop of a `ValidatedForm`.
|
26
|
+
*/
|
12
27
|
export declare type Validator<DataType> = {
|
13
|
-
validate: (unvalidatedData:
|
14
|
-
validateField: (unvalidatedData:
|
28
|
+
validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
|
29
|
+
validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
|
15
30
|
};
|
File without changes
|
File without changes
|
@@ -1,6 +1,8 @@
|
|
1
1
|
import * as yup from "yup";
|
2
2
|
import { z } from "zod";
|
3
3
|
import { withYup } from "..";
|
4
|
+
import { objectFromPathEntries } from "../internal/flatten";
|
5
|
+
import { TestFormData } from "../test-data/testFormData";
|
4
6
|
import { withZod } from "./withZod";
|
5
7
|
const validationTestCases = [
|
6
8
|
{
|
@@ -9,6 +11,17 @@ const validationTestCases = [
|
|
9
11
|
firstName: yup.string().required(),
|
10
12
|
lastName: yup.string().required(),
|
11
13
|
age: yup.number(),
|
14
|
+
address: yup
|
15
|
+
.object({
|
16
|
+
streetAddress: yup.string().required(),
|
17
|
+
city: yup.string().required(),
|
18
|
+
country: yup.string().required(),
|
19
|
+
})
|
20
|
+
.required(),
|
21
|
+
pets: yup.array().of(yup.object({
|
22
|
+
animal: yup.string().required(),
|
23
|
+
name: yup.string().required(),
|
24
|
+
})),
|
12
25
|
})),
|
13
26
|
},
|
14
27
|
{
|
@@ -17,6 +30,18 @@ const validationTestCases = [
|
|
17
30
|
firstName: z.string().nonempty(),
|
18
31
|
lastName: z.string().nonempty(),
|
19
32
|
age: z.optional(z.number()),
|
33
|
+
address: z.preprocess((value) => (value == null ? {} : value), z.object({
|
34
|
+
streetAddress: z.string().nonempty(),
|
35
|
+
city: z.string().nonempty(),
|
36
|
+
country: z.string().nonempty(),
|
37
|
+
})),
|
38
|
+
pets: z
|
39
|
+
.object({
|
40
|
+
animal: z.string().nonempty(),
|
41
|
+
name: z.string().nonempty(),
|
42
|
+
})
|
43
|
+
.array()
|
44
|
+
.optional(),
|
20
45
|
})),
|
21
46
|
},
|
22
47
|
];
|
@@ -26,41 +51,168 @@ describe("Validation", () => {
|
|
26
51
|
describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
|
27
52
|
describe("validate", () => {
|
28
53
|
it("should return the data when valid", () => {
|
29
|
-
const
|
54
|
+
const person = {
|
30
55
|
firstName: "John",
|
31
56
|
lastName: "Doe",
|
32
57
|
age: 30,
|
58
|
+
address: {
|
59
|
+
streetAddress: "123 Main St",
|
60
|
+
city: "Anytown",
|
61
|
+
country: "USA",
|
62
|
+
},
|
63
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
33
64
|
};
|
34
|
-
expect(validator.validate(
|
35
|
-
data:
|
65
|
+
expect(validator.validate(person)).toEqual({
|
66
|
+
data: person,
|
36
67
|
error: undefined,
|
37
68
|
});
|
38
69
|
});
|
39
70
|
it("should return field errors when invalid", () => {
|
40
|
-
const obj = { age: "hi!" };
|
71
|
+
const obj = { age: "hi!", pets: [{ animal: "dog" }] };
|
41
72
|
expect(validator.validate(obj)).toEqual({
|
42
73
|
data: undefined,
|
43
74
|
error: {
|
44
75
|
firstName: anyString,
|
45
76
|
lastName: anyString,
|
46
77
|
age: anyString,
|
78
|
+
"address.city": anyString,
|
79
|
+
"address.country": anyString,
|
80
|
+
"address.streetAddress": anyString,
|
81
|
+
"pets[0].name": anyString,
|
82
|
+
_submittedData: obj,
|
83
|
+
},
|
84
|
+
});
|
85
|
+
});
|
86
|
+
it("should unflatten data when validating", () => {
|
87
|
+
const data = {
|
88
|
+
firstName: "John",
|
89
|
+
lastName: "Doe",
|
90
|
+
age: 30,
|
91
|
+
"address.streetAddress": "123 Main St",
|
92
|
+
"address.city": "Anytown",
|
93
|
+
"address.country": "USA",
|
94
|
+
"pets[0].animal": "dog",
|
95
|
+
"pets[0].name": "Fido",
|
96
|
+
};
|
97
|
+
expect(validator.validate(data)).toEqual({
|
98
|
+
data: {
|
99
|
+
firstName: "John",
|
100
|
+
lastName: "Doe",
|
101
|
+
age: 30,
|
102
|
+
address: {
|
103
|
+
streetAddress: "123 Main St",
|
104
|
+
city: "Anytown",
|
105
|
+
country: "USA",
|
106
|
+
},
|
107
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
108
|
+
},
|
109
|
+
error: undefined,
|
110
|
+
});
|
111
|
+
});
|
112
|
+
it("should accept FormData directly and return errors", () => {
|
113
|
+
const formData = new TestFormData();
|
114
|
+
formData.set("firstName", "John");
|
115
|
+
formData.set("lastName", "Doe");
|
116
|
+
formData.set("address.streetAddress", "123 Main St");
|
117
|
+
formData.set("address.country", "USA");
|
118
|
+
formData.set("pets[0].animal", "dog");
|
119
|
+
expect(validator.validate(formData)).toEqual({
|
120
|
+
data: undefined,
|
121
|
+
error: {
|
122
|
+
"address.city": anyString,
|
123
|
+
"pets[0].name": anyString,
|
124
|
+
_submittedData: objectFromPathEntries([...formData.entries()]),
|
47
125
|
},
|
48
126
|
});
|
49
127
|
});
|
128
|
+
it("should accept FormData directly and return valid data", () => {
|
129
|
+
const formData = new TestFormData();
|
130
|
+
formData.set("firstName", "John");
|
131
|
+
formData.set("lastName", "Doe");
|
132
|
+
formData.set("address.streetAddress", "123 Main St");
|
133
|
+
formData.set("address.country", "USA");
|
134
|
+
formData.set("address.city", "Anytown");
|
135
|
+
formData.set("pets[0].animal", "dog");
|
136
|
+
formData.set("pets[0].name", "Fido");
|
137
|
+
expect(validator.validate(formData)).toEqual({
|
138
|
+
data: {
|
139
|
+
firstName: "John",
|
140
|
+
lastName: "Doe",
|
141
|
+
address: {
|
142
|
+
streetAddress: "123 Main St",
|
143
|
+
country: "USA",
|
144
|
+
city: "Anytown",
|
145
|
+
},
|
146
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
147
|
+
},
|
148
|
+
error: undefined,
|
149
|
+
});
|
150
|
+
});
|
50
151
|
});
|
51
152
|
describe("validateField", () => {
|
52
153
|
it("should not return an error if field is valid", () => {
|
53
|
-
const
|
154
|
+
const person = {
|
54
155
|
firstName: "John",
|
55
156
|
lastName: {}, // invalid, but we should only be validating firstName
|
56
157
|
};
|
57
|
-
expect(validator.validateField(
|
158
|
+
expect(validator.validateField(person, "firstName")).toEqual({
|
159
|
+
error: undefined,
|
160
|
+
});
|
161
|
+
});
|
162
|
+
it("should not return an error if a nested field is valid", () => {
|
163
|
+
const person = {
|
164
|
+
firstName: "John",
|
165
|
+
lastName: {},
|
166
|
+
address: {
|
167
|
+
streetAddress: "123 Main St",
|
168
|
+
city: "Anytown",
|
169
|
+
country: "USA",
|
170
|
+
},
|
171
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
172
|
+
};
|
173
|
+
expect(validator.validateField(person, "address.streetAddress")).toEqual({
|
174
|
+
error: undefined,
|
175
|
+
});
|
176
|
+
expect(validator.validateField(person, "address.city")).toEqual({
|
177
|
+
error: undefined,
|
178
|
+
});
|
179
|
+
expect(validator.validateField(person, "address.country")).toEqual({
|
180
|
+
error: undefined,
|
181
|
+
});
|
182
|
+
expect(validator.validateField(person, "pets[0].animal")).toEqual({
|
183
|
+
error: undefined,
|
184
|
+
});
|
185
|
+
expect(validator.validateField(person, "pets[0].name")).toEqual({
|
58
186
|
error: undefined,
|
59
187
|
});
|
60
188
|
});
|
61
189
|
it("should return an error if field is invalid", () => {
|
62
|
-
const
|
63
|
-
|
190
|
+
const person = {
|
191
|
+
firstName: "John",
|
192
|
+
lastName: {},
|
193
|
+
address: {
|
194
|
+
streetAddress: "123 Main St",
|
195
|
+
city: 1234,
|
196
|
+
},
|
197
|
+
};
|
198
|
+
expect(validator.validateField(person, "lastName")).toEqual({
|
199
|
+
error: anyString,
|
200
|
+
});
|
201
|
+
});
|
202
|
+
it("should return an error if a nested field is invalid", () => {
|
203
|
+
const person = {
|
204
|
+
firstName: "John",
|
205
|
+
lastName: {},
|
206
|
+
address: {
|
207
|
+
streetAddress: "123 Main St",
|
208
|
+
city: 1234,
|
209
|
+
},
|
210
|
+
pets: [{ animal: "dog" }],
|
211
|
+
};
|
212
|
+
expect(validator.validateField(person, "address.country")).toEqual({
|
213
|
+
error: anyString,
|
214
|
+
});
|
215
|
+
expect(validator.validateField(person, "pets[0].name")).toEqual({
|
64
216
|
error: anyString,
|
65
217
|
});
|
66
218
|
});
|
@@ -90,6 +242,7 @@ describe("withZod", () => {
|
|
90
242
|
type: anyString,
|
91
243
|
bar: anyString,
|
92
244
|
foo: anyString,
|
245
|
+
_submittedData: obj,
|
93
246
|
},
|
94
247
|
});
|
95
248
|
});
|
@@ -108,6 +261,7 @@ describe("withZod", () => {
|
|
108
261
|
error: {
|
109
262
|
field1: anyString,
|
110
263
|
field2: anyString,
|
264
|
+
_submittedData: obj,
|
111
265
|
},
|
112
266
|
});
|
113
267
|
expect(validator.validateField(obj, "field1")).toEqual({
|
@@ -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>>;
|
@@ -1,3 +1,4 @@
|
|
1
|
+
import { createValidator } from "./createValidator";
|
1
2
|
const validationErrorToFieldErrors = (error) => {
|
2
3
|
const fieldErrors = {};
|
3
4
|
error.inner.forEach((innerError) => {
|
@@ -7,28 +8,33 @@ const validationErrorToFieldErrors = (error) => {
|
|
7
8
|
});
|
8
9
|
return fieldErrors;
|
9
10
|
};
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
error:
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
11
|
+
/**
|
12
|
+
* Create a `Validator` using a `yup` schema.
|
13
|
+
*/
|
14
|
+
export const withYup = (validationSchema) => {
|
15
|
+
return createValidator({
|
16
|
+
validate: (data) => {
|
17
|
+
try {
|
18
|
+
const validated = validationSchema.validateSync(data, {
|
19
|
+
abortEarly: false,
|
20
|
+
});
|
21
|
+
return { data: validated, error: undefined };
|
22
|
+
}
|
23
|
+
catch (err) {
|
24
|
+
return {
|
25
|
+
error: validationErrorToFieldErrors(err),
|
26
|
+
data: undefined,
|
27
|
+
};
|
28
|
+
}
|
29
|
+
},
|
30
|
+
validateField: (data, field) => {
|
31
|
+
try {
|
32
|
+
validationSchema.validateSyncAt(field, data);
|
33
|
+
return {};
|
34
|
+
}
|
35
|
+
catch (err) {
|
36
|
+
return { error: err.message };
|
37
|
+
}
|
38
|
+
},
|
39
|
+
});
|
40
|
+
};
|
@@ -1,3 +1,6 @@
|
|
1
|
+
import isEqual from "lodash/isEqual";
|
2
|
+
import toPath from "lodash/toPath";
|
3
|
+
import { createValidator } from "./createValidator";
|
1
4
|
const getIssuesForError = (err) => {
|
2
5
|
return err.issues.flatMap((issue) => {
|
3
6
|
if ("unionErrors" in issue) {
|
@@ -8,15 +11,24 @@ const getIssuesForError = (err) => {
|
|
8
11
|
}
|
9
12
|
});
|
10
13
|
};
|
14
|
+
function pathToString(array) {
|
15
|
+
return array.reduce(function (string, item) {
|
16
|
+
var prefix = string === "" ? "" : ".";
|
17
|
+
return string + (isNaN(Number(item)) ? prefix + item : "[" + item + "]");
|
18
|
+
}, "");
|
19
|
+
}
|
20
|
+
/**
|
21
|
+
* Create a validator using a `zod` schema.
|
22
|
+
*/
|
11
23
|
export function withZod(zodSchema) {
|
12
|
-
return {
|
24
|
+
return createValidator({
|
13
25
|
validate: (value) => {
|
14
26
|
const result = zodSchema.safeParse(value);
|
15
27
|
if (result.success)
|
16
28
|
return { data: result.data, error: undefined };
|
17
29
|
const fieldErrors = {};
|
18
30
|
getIssuesForError(result.error).forEach((issue) => {
|
19
|
-
const path = issue.path
|
31
|
+
const path = pathToString(issue.path);
|
20
32
|
if (!fieldErrors[path])
|
21
33
|
fieldErrors[path] = issue.message;
|
22
34
|
});
|
@@ -28,8 +40,11 @@ export function withZod(zodSchema) {
|
|
28
40
|
if (result.success)
|
29
41
|
return { error: undefined };
|
30
42
|
return {
|
31
|
-
error: (_a = getIssuesForError(result.error).find((issue) =>
|
43
|
+
error: (_a = getIssuesForError(result.error).find((issue) => {
|
44
|
+
const allPathsAsString = issue.path.map((p) => `${p}`);
|
45
|
+
return isEqual(allPathsAsString, toPath(field));
|
46
|
+
})) === null || _a === void 0 ? void 0 : _a.message,
|
32
47
|
};
|
33
48
|
},
|
34
|
-
};
|
49
|
+
});
|
35
50
|
}
|
package/build/ValidatedForm.d.ts
CHANGED
@@ -2,10 +2,44 @@ 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>;
|
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;
|
10
41
|
} & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
|
11
|
-
|
42
|
+
/**
|
43
|
+
* The primary form component of `remix-validated-form`.
|
44
|
+
*/
|
45
|
+
export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }: FormProps<DataType>): JSX.Element;
|
package/build/ValidatedForm.js
CHANGED
@@ -9,36 +9,87 @@ const react_1 = require("@remix-run/react");
|
|
9
9
|
const react_2 = require("react");
|
10
10
|
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
|
11
11
|
const formContext_1 = require("./internal/formContext");
|
12
|
+
const submissionCallbacks_1 = require("./internal/submissionCallbacks");
|
12
13
|
const util_1 = require("./internal/util");
|
13
|
-
function
|
14
|
+
function useFieldErrorsFromBackend(fetcher, subaction) {
|
15
|
+
var _a, _b;
|
14
16
|
const actionData = (0, react_1.useActionData)();
|
15
|
-
|
16
|
-
|
17
|
-
|
17
|
+
if (fetcher)
|
18
|
+
return (_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors;
|
19
|
+
if (!actionData)
|
20
|
+
return null;
|
21
|
+
if (actionData.fieldErrors) {
|
22
|
+
const submittedData = (_b = actionData.fieldErrors) === null || _b === void 0 ? void 0 : _b._submittedData;
|
23
|
+
const subactionsMatch = subaction
|
24
|
+
? subaction === (submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction)
|
25
|
+
: !(submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction);
|
26
|
+
return subactionsMatch ? actionData.fieldErrors : null;
|
27
|
+
}
|
28
|
+
return null;
|
29
|
+
}
|
30
|
+
function useFieldErrors(fieldErrorsFromBackend) {
|
31
|
+
const [fieldErrors, setFieldErrors] = (0, react_2.useState)(fieldErrorsFromBackend !== null && fieldErrorsFromBackend !== void 0 ? fieldErrorsFromBackend : {});
|
18
32
|
(0, react_2.useEffect)(() => {
|
19
|
-
if (
|
20
|
-
setFieldErrors(
|
21
|
-
}, [
|
33
|
+
if (fieldErrorsFromBackend)
|
34
|
+
setFieldErrors(fieldErrorsFromBackend);
|
35
|
+
}, [fieldErrorsFromBackend]);
|
22
36
|
return [fieldErrors, setFieldErrors];
|
23
37
|
}
|
24
|
-
const useIsSubmitting = (action, fetcher) => {
|
38
|
+
const useIsSubmitting = (action, subaction, fetcher) => {
|
25
39
|
const actionForCurrentPage = (0, react_1.useFormAction)();
|
26
40
|
const pendingFormSubmit = (0, react_1.useTransition)().submission;
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
41
|
+
if (fetcher)
|
42
|
+
return fetcher.state === "submitting";
|
43
|
+
if (!pendingFormSubmit)
|
44
|
+
return false;
|
45
|
+
const { formData, action: pendingAction } = pendingFormSubmit;
|
46
|
+
const pendingSubAction = formData.get("subaction");
|
47
|
+
const expectedAction = action !== null && action !== void 0 ? action : actionForCurrentPage;
|
48
|
+
if (subaction)
|
49
|
+
return expectedAction === pendingAction && subaction === pendingSubAction;
|
50
|
+
return expectedAction === pendingAction && !pendingSubAction;
|
31
51
|
};
|
32
|
-
const getDataFromForm = (el) =>
|
33
|
-
|
52
|
+
const getDataFromForm = (el) => new FormData(el);
|
53
|
+
/**
|
54
|
+
* The purpose for this logic is to handle validation errors when javascript is disabled.
|
55
|
+
* Normally (without js), when a form is submitted and the action returns the validation errors,
|
56
|
+
* the form will be reset. The errors will be displayed on the correct fields,
|
57
|
+
* but all the values in the form will be gone. This is not good UX.
|
58
|
+
*
|
59
|
+
* To get around this, we return the submitted form data from the server,
|
60
|
+
* and use those to populate the form via `defaultValues`.
|
61
|
+
* This results in a more seamless UX akin to what you would see when js is enabled.
|
62
|
+
*
|
63
|
+
* One potential downside is that resetting the form will reset the form
|
64
|
+
* to the _new_ default values that were returned from the server with the validation errors.
|
65
|
+
* However, this case is less of a problem than the janky UX caused by losing the form values.
|
66
|
+
* It will only ever be a problem if the form includes a `<button type="reset" />`
|
67
|
+
* and only if JS is disabled.
|
68
|
+
*/
|
69
|
+
function useDefaultValues(fieldErrors, defaultValues) {
|
70
|
+
const defaultsFromValidationError = fieldErrors === null || fieldErrors === void 0 ? void 0 : fieldErrors._submittedData;
|
71
|
+
return defaultsFromValidationError !== null && defaultsFromValidationError !== void 0 ? defaultsFromValidationError : defaultValues;
|
72
|
+
}
|
73
|
+
/**
|
74
|
+
* The primary form component of `remix-validated-form`.
|
75
|
+
*/
|
76
|
+
function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }) {
|
34
77
|
var _a;
|
35
|
-
const
|
36
|
-
const
|
78
|
+
const fieldErrorsFromBackend = useFieldErrorsFromBackend(fetcher, subaction);
|
79
|
+
const [fieldErrors, setFieldErrors] = useFieldErrors(fieldErrorsFromBackend);
|
80
|
+
const isSubmitting = useIsSubmitting(action, subaction, fetcher);
|
81
|
+
const defaultsToUse = useDefaultValues(fieldErrorsFromBackend, defaultValues);
|
37
82
|
const formRef = (0, react_2.useRef)(null);
|
83
|
+
(0, submissionCallbacks_1.useSubmitComplete)(isSubmitting, () => {
|
84
|
+
var _a;
|
85
|
+
if (!fieldErrorsFromBackend) {
|
86
|
+
(_a = formRef.current) === null || _a === void 0 ? void 0 : _a.reset();
|
87
|
+
}
|
88
|
+
});
|
38
89
|
const contextValue = (0, react_2.useMemo)(() => ({
|
39
90
|
fieldErrors,
|
40
91
|
action,
|
41
|
-
defaultValues,
|
92
|
+
defaultValues: defaultsToUse,
|
42
93
|
isSubmitting: isSubmitting !== null && isSubmitting !== void 0 ? isSubmitting : false,
|
43
94
|
clearError: (fieldName) => {
|
44
95
|
setFieldErrors((prev) => (0, util_1.omit)(prev, fieldName));
|
@@ -56,7 +107,7 @@ function ValidatedForm({ validator, onSubmit, children, fetcher, action, default
|
|
56
107
|
}), [
|
57
108
|
fieldErrors,
|
58
109
|
action,
|
59
|
-
|
110
|
+
defaultsToUse,
|
60
111
|
isSubmitting,
|
61
112
|
setFieldErrors,
|
62
113
|
validator,
|
@@ -71,6 +122,11 @@ function ValidatedForm({ validator, onSubmit, children, fetcher, action, default
|
|
71
122
|
else {
|
72
123
|
onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, event);
|
73
124
|
}
|
74
|
-
},
|
125
|
+
}, onReset: (event) => {
|
126
|
+
onReset === null || onReset === void 0 ? void 0 : onReset(event);
|
127
|
+
if (event.defaultPrevented)
|
128
|
+
return;
|
129
|
+
setFieldErrors({});
|
130
|
+
}, children: (0, jsx_runtime_1.jsxs)(formContext_1.FormContext.Provider, { value: contextValue, children: [(0, jsx_runtime_1.jsx)("input", { type: "hidden", value: subaction, name: "subaction" }, void 0), children] }, void 0) }, void 0));
|
75
131
|
}
|
76
132
|
exports.ValidatedForm = ValidatedForm;
|