remix-validated-form 1.1.1-beta.0 → 2.0.1-beta.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/.turbo/turbo-build.log +9 -0
- package/.turbo/turbo-dev.log +0 -0
- package/browser/ValidatedForm.d.ts +22 -0
- package/browser/ValidatedForm.js +4 -1
- package/browser/hooks.d.ts +28 -3
- package/browser/hooks.js +12 -1
- package/browser/index.d.ts +2 -0
- package/browser/index.js +1 -0
- package/browser/{flatten.d.ts → internal/flatten.d.ts} +2 -3
- package/browser/{flatten.js → internal/flatten.js} +2 -8
- package/browser/internal/formContext.d.ts +18 -0
- package/browser/internal/formContext.js +0 -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 +5 -1
- package/browser/validation/createValidator.js +15 -4
- package/browser/validation/types.d.ts +9 -0
- package/browser/validation/types.js +0 -0
- package/browser/validation/validation.test.d.ts +0 -0
- package/browser/validation/validation.test.js +65 -0
- package/browser/validation/withYup.d.ts +3 -0
- package/browser/validation/withYup.js +3 -0
- package/browser/validation/withZod.d.ts +3 -0
- package/browser/validation/withZod.js +3 -0
- package/build/ValidatedForm.d.ts +22 -0
- package/build/ValidatedForm.js +4 -1
- package/build/hooks.d.ts +28 -3
- package/build/hooks.js +12 -1
- package/build/index.d.ts +2 -0
- package/build/index.js +1 -0
- package/build/{flatten.d.ts → internal/flatten.d.ts} +2 -3
- package/build/{flatten.js → internal/flatten.js} +4 -10
- package/build/internal/formContext.d.ts +18 -0
- package/build/internal/formContext.js +0 -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 +5 -1
- package/build/validation/createValidator.js +15 -4
- package/build/validation/types.d.ts +9 -0
- package/build/validation/types.js +0 -0
- package/build/validation/validation.test.d.ts +0 -0
- package/build/validation/validation.test.js +65 -0
- package/build/validation/withYup.d.ts +3 -0
- package/build/validation/withYup.js +3 -0
- package/build/validation/withZod.d.ts +3 -0
- package/build/validation/withZod.js +3 -0
- package/jest.config.js +5 -0
- package/package.json +7 -32
- package/src/ValidatedForm.tsx +151 -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/util.ts +23 -0
- package/src/server.ts +10 -0
- package/src/test-data/testFormData.ts +55 -0
- package/src/validation/createValidator.ts +24 -0
- package/src/validation/types.ts +26 -0
- package/src/validation/validation.test.ts +317 -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 -10
- package/LICENSE +0 -21
- package/README.md +0 -230
- package/sample-app/.env +0 -7
- package/sample-app/README.md +0 -53
- package/sample-app/app/components/ErrorBox.tsx +0 -34
- package/sample-app/app/components/FormInput.tsx +0 -40
- package/sample-app/app/components/FormSelect.tsx +0 -37
- package/sample-app/app/components/SubjectForm.tsx +0 -150
- package/sample-app/app/entry.client.tsx +0 -4
- package/sample-app/app/entry.server.tsx +0 -21
- package/sample-app/app/root.tsx +0 -92
- package/sample-app/app/routes/index.tsx +0 -5
- package/sample-app/app/routes/subjects/$id.edit.tsx +0 -100
- package/sample-app/app/routes/subjects/index.tsx +0 -112
- package/sample-app/app/routes/subjects/new.tsx +0 -48
- package/sample-app/app/services/db.server.ts +0 -23
- package/sample-app/app/types.ts +0 -6
- package/sample-app/package-lock.json +0 -4617
- package/sample-app/package.json +0 -36
- package/sample-app/prisma/dev.db +0 -0
- package/sample-app/prisma/schema.prisma +0 -34
- package/sample-app/public/favicon.ico +0 -0
- package/sample-app/remix.config.js +0 -10
- package/sample-app/remix.env.d.ts +0 -2
@@ -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
|
};
|
File without changes
|
package/build/internal/util.d.ts
CHANGED
File without changes
|
package/build/internal/util.js
CHANGED
File without changes
|
package/build/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/build/server.js
CHANGED
@@ -2,5 +2,10 @@
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
3
|
exports.validationError = void 0;
|
4
4
|
const server_runtime_1 = require("@remix-run/server-runtime");
|
5
|
+
/**
|
6
|
+
* Takes the errors from a `Validator` and returns a `Response`.
|
7
|
+
* The `ValidatedForm` on the frontend will automatically display the errors
|
8
|
+
* if this is returned from the action.
|
9
|
+
*/
|
5
10
|
const validationError = (errors) => (0, server_runtime_1.json)({ fieldErrors: errors }, { status: 422 });
|
6
11
|
exports.validationError = validationError;
|
@@ -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,50 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.TestFormData = void 0;
|
4
|
+
// Copied from remix to use in tests
|
5
|
+
// https://github.com/remix-run/remix/blob/a69a631cb5add72d5fb24211ab2a0be367b6f2fd/packages/remix-node/form-data.ts
|
6
|
+
class TestFormData {
|
7
|
+
constructor(body) {
|
8
|
+
this._params = new URLSearchParams(body);
|
9
|
+
}
|
10
|
+
append(name, value, fileName) {
|
11
|
+
if (typeof value !== "string") {
|
12
|
+
throw new Error("formData.append can only accept a string");
|
13
|
+
}
|
14
|
+
this._params.append(name, value);
|
15
|
+
}
|
16
|
+
delete(name) {
|
17
|
+
this._params.delete(name);
|
18
|
+
}
|
19
|
+
get(name) {
|
20
|
+
return this._params.get(name);
|
21
|
+
}
|
22
|
+
getAll(name) {
|
23
|
+
return this._params.getAll(name);
|
24
|
+
}
|
25
|
+
has(name) {
|
26
|
+
return this._params.has(name);
|
27
|
+
}
|
28
|
+
set(name, value, fileName) {
|
29
|
+
if (typeof value !== "string") {
|
30
|
+
throw new Error("formData.set can only accept a string");
|
31
|
+
}
|
32
|
+
this._params.set(name, value);
|
33
|
+
}
|
34
|
+
forEach(callbackfn, thisArg) {
|
35
|
+
this._params.forEach(callbackfn, thisArg);
|
36
|
+
}
|
37
|
+
entries() {
|
38
|
+
return this._params.entries();
|
39
|
+
}
|
40
|
+
keys() {
|
41
|
+
return this._params.keys();
|
42
|
+
}
|
43
|
+
values() {
|
44
|
+
return this._params.values();
|
45
|
+
}
|
46
|
+
*[Symbol.iterator]() {
|
47
|
+
yield* this._params;
|
48
|
+
}
|
49
|
+
}
|
50
|
+
exports.TestFormData = TestFormData;
|
@@ -1,3 +1,7 @@
|
|
1
1
|
import { Validator } from "..";
|
2
|
-
/**
|
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,12 +1,23 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
3
|
exports.createValidator = void 0;
|
4
|
-
const flatten_1 = require("../flatten");
|
5
|
-
|
4
|
+
const flatten_1 = require("../internal/flatten");
|
5
|
+
const preprocessFormData = (data) => {
|
6
|
+
// A slightly janky way of determining if the data is a FormData object
|
7
|
+
// since node doesn't really have FormData
|
8
|
+
if ("entries" in data && typeof data.entries === "function")
|
9
|
+
return (0, flatten_1.objectFromPathEntries)([...data.entries()]);
|
10
|
+
return (0, flatten_1.objectFromPathEntries)(Object.entries(data));
|
11
|
+
};
|
12
|
+
/**
|
13
|
+
* Used to create a validator for a form.
|
14
|
+
* It provides built-in handling for unflattening nested objects and
|
15
|
+
* extracting the values from FormData.
|
16
|
+
*/
|
6
17
|
function createValidator(validator) {
|
7
18
|
return {
|
8
|
-
validate: (value) => validator.validate((
|
9
|
-
validateField: (data, field) => validator.validateField((
|
19
|
+
validate: (value) => validator.validate(preprocessFormData(value)),
|
20
|
+
validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
|
10
21
|
};
|
11
22
|
}
|
12
23
|
exports.createValidator = createValidator;
|
@@ -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;
|
File without changes
|
File without changes
|
@@ -22,6 +22,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
22
|
const yup = __importStar(require("yup"));
|
23
23
|
const zod_1 = require("zod");
|
24
24
|
const __1 = require("..");
|
25
|
+
const testFormData_1 = require("../test-data/testFormData");
|
25
26
|
const withZod_1 = require("./withZod");
|
26
27
|
const validationTestCases = [
|
27
28
|
{
|
@@ -101,6 +102,70 @@ describe("Validation", () => {
|
|
101
102
|
},
|
102
103
|
});
|
103
104
|
});
|
105
|
+
it("should unflatten data when validating", () => {
|
106
|
+
const data = {
|
107
|
+
firstName: "John",
|
108
|
+
lastName: "Doe",
|
109
|
+
age: 30,
|
110
|
+
"address.streetAddress": "123 Main St",
|
111
|
+
"address.city": "Anytown",
|
112
|
+
"address.country": "USA",
|
113
|
+
"pets[0].animal": "dog",
|
114
|
+
"pets[0].name": "Fido",
|
115
|
+
};
|
116
|
+
expect(validator.validate(data)).toEqual({
|
117
|
+
data: {
|
118
|
+
firstName: "John",
|
119
|
+
lastName: "Doe",
|
120
|
+
age: 30,
|
121
|
+
address: {
|
122
|
+
streetAddress: "123 Main St",
|
123
|
+
city: "Anytown",
|
124
|
+
country: "USA",
|
125
|
+
},
|
126
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
127
|
+
},
|
128
|
+
error: undefined,
|
129
|
+
});
|
130
|
+
});
|
131
|
+
it("should accept FormData directly and return errors", () => {
|
132
|
+
const formData = new testFormData_1.TestFormData();
|
133
|
+
formData.set("firstName", "John");
|
134
|
+
formData.set("lastName", "Doe");
|
135
|
+
formData.set("address.streetAddress", "123 Main St");
|
136
|
+
formData.set("address.country", "USA");
|
137
|
+
formData.set("pets[0].animal", "dog");
|
138
|
+
expect(validator.validate(formData)).toEqual({
|
139
|
+
data: undefined,
|
140
|
+
error: {
|
141
|
+
"address.city": anyString,
|
142
|
+
"pets[0].name": anyString,
|
143
|
+
},
|
144
|
+
});
|
145
|
+
});
|
146
|
+
it("should accept FormData directly and return valid data", () => {
|
147
|
+
const formData = new testFormData_1.TestFormData();
|
148
|
+
formData.set("firstName", "John");
|
149
|
+
formData.set("lastName", "Doe");
|
150
|
+
formData.set("address.streetAddress", "123 Main St");
|
151
|
+
formData.set("address.country", "USA");
|
152
|
+
formData.set("address.city", "Anytown");
|
153
|
+
formData.set("pets[0].animal", "dog");
|
154
|
+
formData.set("pets[0].name", "Fido");
|
155
|
+
expect(validator.validate(formData)).toEqual({
|
156
|
+
data: {
|
157
|
+
firstName: "John",
|
158
|
+
lastName: "Doe",
|
159
|
+
address: {
|
160
|
+
streetAddress: "123 Main St",
|
161
|
+
country: "USA",
|
162
|
+
city: "Anytown",
|
163
|
+
},
|
164
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
165
|
+
},
|
166
|
+
error: undefined,
|
167
|
+
});
|
168
|
+
});
|
104
169
|
});
|
105
170
|
describe("validateField", () => {
|
106
171
|
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>>;
|
@@ -11,6 +11,9 @@ const validationErrorToFieldErrors = (error) => {
|
|
11
11
|
});
|
12
12
|
return fieldErrors;
|
13
13
|
};
|
14
|
+
/**
|
15
|
+
* Create a `Validator` using a `yup` schema.
|
16
|
+
*/
|
14
17
|
const withYup = (validationSchema) => {
|
15
18
|
return (0, createValidator_1.createValidator)({
|
16
19
|
validate: (data) => {
|
@@ -23,6 +23,9 @@ function pathToString(array) {
|
|
23
23
|
return string + (isNaN(Number(item)) ? prefix + item : "[" + item + "]");
|
24
24
|
}, "");
|
25
25
|
}
|
26
|
+
/**
|
27
|
+
* Create a validator using a `zod` schema.
|
28
|
+
*/
|
26
29
|
function withZod(zodSchema) {
|
27
30
|
return (0, createValidator_1.createValidator)({
|
28
31
|
validate: (value) => {
|
package/jest.config.js
CHANGED
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "remix-validated-form",
|
3
|
-
"version": "
|
3
|
+
"version": "2.0.1-beta.0",
|
4
4
|
"description": "Form component and utils for easy form validation in remix",
|
5
5
|
"browser": "./browser/index.js",
|
6
6
|
"main": "./build/index.js",
|
@@ -10,17 +10,12 @@
|
|
10
10
|
},
|
11
11
|
"sideEffects": false,
|
12
12
|
"scripts": {
|
13
|
-
"
|
14
|
-
"build
|
15
|
-
"build:
|
16
|
-
"build:
|
17
|
-
"build:sample": "tsc --project tsconfig.json --module CommonJS --outDir ./sample-app/remix-validated-form",
|
18
|
-
"sample-app": "npm run build:sample && cd sample-app && npm run dev",
|
13
|
+
"dev": "tsc --module ESNext --outDir ./browser --watch",
|
14
|
+
"build": "npm run build:browser && npm run build:main",
|
15
|
+
"build:browser": "tsc --module ESNext --outDir ./browser",
|
16
|
+
"build:main": "tsc --module CommonJS --outDir ./build",
|
19
17
|
"test": "jest src",
|
20
18
|
"test:watch": "jest src --watch",
|
21
|
-
"lint": "eslint .",
|
22
|
-
"prettier": "prettier . --write",
|
23
|
-
"prepare": "husky install",
|
24
19
|
"prepublishOnly": "npm run build:browser && npm run build:main"
|
25
20
|
},
|
26
21
|
"author": {
|
@@ -48,25 +43,10 @@
|
|
48
43
|
"@types/jest": "^27.0.3",
|
49
44
|
"@types/lodash": "^4.14.178",
|
50
45
|
"@types/react": "^17.0.37",
|
51
|
-
"@typescript-eslint/eslint-plugin": "^5.6.0",
|
52
|
-
"@typescript-eslint/parser": "^5.6.0",
|
53
|
-
"babel-eslint": "^10.1.0",
|
54
|
-
"eslint": "^7.32.0",
|
55
|
-
"eslint-config-react-app": "^6.0.0",
|
56
|
-
"eslint-plugin-cypress": "^2.12.1",
|
57
|
-
"eslint-plugin-flowtype": "^8.0.3",
|
58
|
-
"eslint-plugin-import": "^2.25.3",
|
59
|
-
"eslint-plugin-jsx-a11y": "^6.5.1",
|
60
|
-
"eslint-plugin-prettier": "^4.0.0",
|
61
|
-
"eslint-plugin-react": "^7.27.1",
|
62
|
-
"eslint-plugin-react-hooks": "^4.3.0",
|
63
46
|
"fetch-blob": "^3.1.3",
|
64
|
-
"husky": "^7.0.4",
|
65
|
-
"jest": "^27.4.4",
|
66
|
-
"lint-staged": "^12.1.2",
|
67
|
-
"prettier": "^2.5.1",
|
68
47
|
"react": "^17.0.2",
|
69
48
|
"ts-jest": "^27.1.1",
|
49
|
+
"tsconfig": "*",
|
70
50
|
"typescript": "^4.5.3",
|
71
51
|
"yup": "^0.32.11",
|
72
52
|
"zod": "^3.11.6"
|
@@ -75,10 +55,5 @@
|
|
75
55
|
"lodash": "^4.17.21",
|
76
56
|
"tiny-invariant": "^1.2.0"
|
77
57
|
},
|
78
|
-
"
|
79
|
-
"**/*.{ts,tsx,js,jsx}": [
|
80
|
-
"prettier --write",
|
81
|
-
"eslint --cache --fix"
|
82
|
-
]
|
83
|
-
}
|
58
|
+
"gitHead": "dab8f221d7c0c5131504215f5c19e3ecdfef97fb"
|
84
59
|
}
|
@@ -0,0 +1,151 @@
|
|
1
|
+
import {
|
2
|
+
Form as RemixForm,
|
3
|
+
useActionData,
|
4
|
+
useFetcher,
|
5
|
+
useFormAction,
|
6
|
+
useTransition,
|
7
|
+
} from "@remix-run/react";
|
8
|
+
import React, {
|
9
|
+
ComponentProps,
|
10
|
+
useEffect,
|
11
|
+
useMemo,
|
12
|
+
useRef,
|
13
|
+
useState,
|
14
|
+
} from "react";
|
15
|
+
import invariant from "tiny-invariant";
|
16
|
+
import { FormContext, FormContextValue } from "./internal/formContext";
|
17
|
+
import { omit, mergeRefs } from "./internal/util";
|
18
|
+
import { FieldErrors, Validator } from "./validation/types";
|
19
|
+
|
20
|
+
export type FormProps<DataType> = {
|
21
|
+
/**
|
22
|
+
* A `Validator` object that describes how to validate the form.
|
23
|
+
*/
|
24
|
+
validator: Validator<DataType>;
|
25
|
+
/**
|
26
|
+
* A submit callback that gets called when the form is submitted
|
27
|
+
* after all validations have been run.
|
28
|
+
*/
|
29
|
+
onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void;
|
30
|
+
/**
|
31
|
+
* Allows you to provide a `fetcher` from remix's `useFetcher` hook.
|
32
|
+
* The form will use the fetcher for loading states, action data, etc
|
33
|
+
* instead of the default form action.
|
34
|
+
*/
|
35
|
+
fetcher?: ReturnType<typeof useFetcher>;
|
36
|
+
/**
|
37
|
+
* Accepts an object of default values for the form
|
38
|
+
* that will automatically be propagated to the form fields via `useField`.
|
39
|
+
*/
|
40
|
+
defaultValues?: Partial<DataType>;
|
41
|
+
/**
|
42
|
+
* A ref to the form element.
|
43
|
+
*/
|
44
|
+
formRef?: React.RefObject<HTMLFormElement>;
|
45
|
+
} & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
|
46
|
+
|
47
|
+
function useFieldErrors(
|
48
|
+
fetcher?: ReturnType<typeof useFetcher>
|
49
|
+
): [FieldErrors, React.Dispatch<React.SetStateAction<FieldErrors>>] {
|
50
|
+
const actionData = useActionData<any>();
|
51
|
+
const dataToUse = fetcher ? fetcher.data : actionData;
|
52
|
+
const fieldErrorsFromAction = dataToUse?.fieldErrors;
|
53
|
+
|
54
|
+
const [fieldErrors, setFieldErrors] = useState<FieldErrors>(
|
55
|
+
fieldErrorsFromAction ?? {}
|
56
|
+
);
|
57
|
+
useEffect(() => {
|
58
|
+
if (fieldErrorsFromAction) setFieldErrors(fieldErrorsFromAction);
|
59
|
+
}, [fieldErrorsFromAction]);
|
60
|
+
|
61
|
+
return [fieldErrors, setFieldErrors];
|
62
|
+
}
|
63
|
+
|
64
|
+
const useIsSubmitting = (
|
65
|
+
action?: string,
|
66
|
+
fetcher?: ReturnType<typeof useFetcher>
|
67
|
+
) => {
|
68
|
+
const actionForCurrentPage = useFormAction();
|
69
|
+
const pendingFormSubmit = useTransition().submission;
|
70
|
+
return fetcher
|
71
|
+
? fetcher.state === "submitting"
|
72
|
+
: pendingFormSubmit &&
|
73
|
+
pendingFormSubmit.action === (action ?? actionForCurrentPage);
|
74
|
+
};
|
75
|
+
|
76
|
+
const getDataFromForm = (el: HTMLFormElement) => new FormData(el);
|
77
|
+
|
78
|
+
/**
|
79
|
+
* The primary form component of `remix-validated-form`.
|
80
|
+
*/
|
81
|
+
export function ValidatedForm<DataType>({
|
82
|
+
validator,
|
83
|
+
onSubmit,
|
84
|
+
children,
|
85
|
+
fetcher,
|
86
|
+
action,
|
87
|
+
defaultValues,
|
88
|
+
formRef: formRefProp,
|
89
|
+
...rest
|
90
|
+
}: FormProps<DataType>) {
|
91
|
+
const [fieldErrors, setFieldErrors] = useFieldErrors(fetcher);
|
92
|
+
const isSubmitting = useIsSubmitting(action, fetcher);
|
93
|
+
|
94
|
+
const formRef = useRef<HTMLFormElement>(null);
|
95
|
+
|
96
|
+
const contextValue = useMemo<FormContextValue>(
|
97
|
+
() => ({
|
98
|
+
fieldErrors,
|
99
|
+
action,
|
100
|
+
defaultValues,
|
101
|
+
isSubmitting: isSubmitting ?? false,
|
102
|
+
clearError: (fieldName) => {
|
103
|
+
setFieldErrors((prev) => omit(prev, fieldName));
|
104
|
+
},
|
105
|
+
validateField: (fieldName) => {
|
106
|
+
invariant(formRef.current, "Cannot find reference to form");
|
107
|
+
const { error } = validator.validateField(
|
108
|
+
getDataFromForm(formRef.current),
|
109
|
+
fieldName as any
|
110
|
+
);
|
111
|
+
if (error) {
|
112
|
+
setFieldErrors((prev) => ({
|
113
|
+
...prev,
|
114
|
+
[fieldName]: error,
|
115
|
+
}));
|
116
|
+
}
|
117
|
+
},
|
118
|
+
}),
|
119
|
+
[
|
120
|
+
fieldErrors,
|
121
|
+
action,
|
122
|
+
defaultValues,
|
123
|
+
isSubmitting,
|
124
|
+
setFieldErrors,
|
125
|
+
validator,
|
126
|
+
]
|
127
|
+
);
|
128
|
+
|
129
|
+
const Form = fetcher?.Form ?? RemixForm;
|
130
|
+
|
131
|
+
return (
|
132
|
+
<Form
|
133
|
+
ref={mergeRefs([formRef, formRefProp])}
|
134
|
+
{...rest}
|
135
|
+
action={action}
|
136
|
+
onSubmit={(event) => {
|
137
|
+
const result = validator.validate(getDataFromForm(event.currentTarget));
|
138
|
+
if (result.error) {
|
139
|
+
event.preventDefault();
|
140
|
+
setFieldErrors(result.error);
|
141
|
+
} else {
|
142
|
+
onSubmit?.(result.data, event);
|
143
|
+
}
|
144
|
+
}}
|
145
|
+
>
|
146
|
+
<FormContext.Provider value={contextValue}>
|
147
|
+
{children}
|
148
|
+
</FormContext.Provider>
|
149
|
+
</Form>
|
150
|
+
);
|
151
|
+
}
|
package/src/hooks.ts
ADDED
@@ -0,0 +1,60 @@
|
|
1
|
+
import get from "lodash/get";
|
2
|
+
import toPath from "lodash/toPath";
|
3
|
+
import { useContext, useMemo } from "react";
|
4
|
+
import { FormContext } from "./internal/formContext";
|
5
|
+
|
6
|
+
export type FieldProps = {
|
7
|
+
/**
|
8
|
+
* The validation error message if there is one.
|
9
|
+
*/
|
10
|
+
error?: string;
|
11
|
+
/**
|
12
|
+
* Clears the error message.
|
13
|
+
*/
|
14
|
+
clearError: () => void;
|
15
|
+
/**
|
16
|
+
* Validates the field.
|
17
|
+
*/
|
18
|
+
validate: () => void;
|
19
|
+
/**
|
20
|
+
* The default value of the field, if there is one.
|
21
|
+
*/
|
22
|
+
defaultValue?: any;
|
23
|
+
};
|
24
|
+
|
25
|
+
/**
|
26
|
+
* Provides the data and helpers necessary to set up a field.
|
27
|
+
*/
|
28
|
+
export const useField = (name: string): FieldProps => {
|
29
|
+
const { fieldErrors, clearError, validateField, defaultValues } =
|
30
|
+
useContext(FormContext);
|
31
|
+
|
32
|
+
const field = useMemo<FieldProps>(
|
33
|
+
() => ({
|
34
|
+
error: fieldErrors[name],
|
35
|
+
clearError: () => {
|
36
|
+
clearError(name);
|
37
|
+
},
|
38
|
+
validate: () => validateField(name),
|
39
|
+
defaultValue: defaultValues
|
40
|
+
? get(defaultValues, toPath(name), undefined)
|
41
|
+
: undefined,
|
42
|
+
}),
|
43
|
+
[clearError, defaultValues, fieldErrors, name, validateField]
|
44
|
+
);
|
45
|
+
|
46
|
+
return field;
|
47
|
+
};
|
48
|
+
|
49
|
+
/**
|
50
|
+
* Provides access to the entire form context.
|
51
|
+
* This is not usually necessary, but can be useful for advanced use cases.
|
52
|
+
*/
|
53
|
+
export const useFormContext = () => useContext(FormContext);
|
54
|
+
|
55
|
+
/**
|
56
|
+
* Returns whether or not the parent form is currently being submitted.
|
57
|
+
* This is different from remix's `useTransition().submission` in that it
|
58
|
+
* is aware of what form it's in and when _that_ form is being submitted.
|
59
|
+
*/
|
60
|
+
export const useIsSubmitting = () => useFormContext().isSubmitting;
|
package/src/index.ts
ADDED
@@ -0,0 +1,8 @@
|
|
1
|
+
export * from "./hooks";
|
2
|
+
export * from "./server";
|
3
|
+
export * from "./ValidatedForm";
|
4
|
+
export * from "./validation/types";
|
5
|
+
export * from "./validation/withYup";
|
6
|
+
export * from "./validation/withZod";
|
7
|
+
export * from "./validation/createValidator";
|
8
|
+
export type { FormContextValue } from "./internal/formContext";
|
@@ -0,0 +1,48 @@
|
|
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
|
+
import { GenericObject } from "..";
|
10
|
+
|
11
|
+
export const objectFromPathEntries = (entries: [string, any][]) =>
|
12
|
+
entries.reduce((acc, [key, value]) => set(acc, key, value), {});
|
13
|
+
|
14
|
+
/** Flatten an object so there are no nested objects or arrays */
|
15
|
+
export function flatten(obj: GenericObject, preserveEmpty = false) {
|
16
|
+
return transform(
|
17
|
+
obj,
|
18
|
+
function (result: GenericObject, value, key) {
|
19
|
+
if (isObject(value)) {
|
20
|
+
let flatMap = mapKeys(
|
21
|
+
flatten(value, preserveEmpty),
|
22
|
+
function (_mvalue, mkey) {
|
23
|
+
if (isArray(value)) {
|
24
|
+
let index = mkey.indexOf(".");
|
25
|
+
if (-1 !== index) {
|
26
|
+
return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
|
27
|
+
}
|
28
|
+
return `${key}[${mkey}]`;
|
29
|
+
}
|
30
|
+
return `${key}.${mkey}`;
|
31
|
+
}
|
32
|
+
);
|
33
|
+
|
34
|
+
assign(result, flatMap);
|
35
|
+
|
36
|
+
// Preverve Empty arrays and objects
|
37
|
+
if (preserveEmpty && keys(flatMap).length === 0) {
|
38
|
+
result[key] = value;
|
39
|
+
}
|
40
|
+
} else {
|
41
|
+
result[key] = value;
|
42
|
+
}
|
43
|
+
|
44
|
+
return result;
|
45
|
+
},
|
46
|
+
{}
|
47
|
+
);
|
48
|
+
}
|