remix-validated-form 2.0.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.
Files changed (101) hide show
  1. package/.turbo/turbo-build.log +9 -0
  2. package/.turbo/turbo-dev.log +0 -0
  3. package/browser/ValidatedForm.d.ts +0 -0
  4. package/browser/ValidatedForm.js +0 -0
  5. package/browser/hooks.d.ts +0 -0
  6. package/browser/hooks.js +0 -0
  7. package/browser/index.d.ts +0 -0
  8. package/browser/index.js +0 -0
  9. package/browser/internal/flatten.d.ts +0 -0
  10. package/browser/internal/flatten.js +0 -0
  11. package/browser/internal/formContext.d.ts +0 -0
  12. package/browser/internal/formContext.js +0 -0
  13. package/browser/internal/util.d.ts +0 -0
  14. package/browser/internal/util.js +0 -0
  15. package/browser/server.d.ts +0 -0
  16. package/browser/server.js +0 -0
  17. package/browser/test-data/testFormData.d.ts +0 -0
  18. package/browser/test-data/testFormData.js +0 -0
  19. package/browser/validation/createValidator.d.ts +0 -0
  20. package/browser/validation/createValidator.js +0 -0
  21. package/browser/validation/types.d.ts +0 -0
  22. package/browser/validation/types.js +0 -0
  23. package/browser/validation/validation.test.d.ts +0 -0
  24. package/browser/validation/validation.test.js +0 -0
  25. package/browser/validation/withYup.d.ts +0 -0
  26. package/browser/validation/withYup.js +0 -0
  27. package/browser/validation/withZod.d.ts +0 -0
  28. package/browser/validation/withZod.js +0 -0
  29. package/build/ValidatedForm.d.ts +0 -0
  30. package/build/ValidatedForm.js +0 -0
  31. package/build/hooks.d.ts +0 -0
  32. package/build/hooks.js +0 -0
  33. package/build/index.d.ts +0 -0
  34. package/build/index.js +0 -0
  35. package/build/internal/flatten.d.ts +0 -0
  36. package/build/internal/flatten.js +0 -0
  37. package/build/internal/formContext.d.ts +0 -0
  38. package/build/internal/formContext.js +0 -0
  39. package/build/internal/util.d.ts +0 -0
  40. package/build/internal/util.js +0 -0
  41. package/build/server.d.ts +0 -0
  42. package/build/server.js +0 -0
  43. package/build/test-data/testFormData.d.ts +0 -0
  44. package/build/test-data/testFormData.js +0 -0
  45. package/build/validation/createValidator.d.ts +0 -0
  46. package/build/validation/createValidator.js +0 -0
  47. package/build/validation/types.d.ts +0 -0
  48. package/build/validation/types.js +0 -0
  49. package/build/validation/validation.test.d.ts +0 -0
  50. package/build/validation/validation.test.js +0 -0
  51. package/build/validation/withYup.d.ts +0 -0
  52. package/build/validation/withYup.js +0 -0
  53. package/build/validation/withZod.d.ts +0 -0
  54. package/build/validation/withZod.js +0 -0
  55. package/jest.config.js +5 -0
  56. package/package.json +7 -32
  57. package/src/ValidatedForm.tsx +151 -0
  58. package/src/hooks.ts +60 -0
  59. package/src/index.ts +8 -0
  60. package/src/internal/flatten.ts +48 -0
  61. package/src/internal/formContext.ts +36 -0
  62. package/src/internal/util.ts +23 -0
  63. package/src/server.ts +10 -0
  64. package/src/test-data/testFormData.ts +55 -0
  65. package/src/validation/createValidator.ts +24 -0
  66. package/src/validation/types.ts +26 -0
  67. package/src/validation/validation.test.ts +317 -0
  68. package/src/validation/withYup.ts +43 -0
  69. package/src/validation/withZod.ts +51 -0
  70. package/tsconfig.json +5 -0
  71. package/.eslintcache +0 -1
  72. package/.eslintignore +0 -1
  73. package/.prettierignore +0 -10
  74. package/LICENSE +0 -21
  75. package/README.md +0 -235
  76. package/browser/flatten.d.ts +0 -4
  77. package/browser/flatten.js +0 -35
  78. package/build/flatten.d.ts +0 -4
  79. package/build/flatten.js +0 -43
  80. package/sample-app/.env +0 -7
  81. package/sample-app/README.md +0 -53
  82. package/sample-app/app/components/ErrorBox.tsx +0 -34
  83. package/sample-app/app/components/FormInput.tsx +0 -40
  84. package/sample-app/app/components/FormSelect.tsx +0 -37
  85. package/sample-app/app/components/SubjectForm.tsx +0 -150
  86. package/sample-app/app/entry.client.tsx +0 -4
  87. package/sample-app/app/entry.server.tsx +0 -21
  88. package/sample-app/app/root.tsx +0 -92
  89. package/sample-app/app/routes/index.tsx +0 -5
  90. package/sample-app/app/routes/subjects/$id.edit.tsx +0 -98
  91. package/sample-app/app/routes/subjects/index.tsx +0 -112
  92. package/sample-app/app/routes/subjects/new.tsx +0 -46
  93. package/sample-app/app/services/db.server.ts +0 -23
  94. package/sample-app/app/types.ts +0 -6
  95. package/sample-app/package-lock.json +0 -10890
  96. package/sample-app/package.json +0 -36
  97. package/sample-app/prisma/dev.db +0 -0
  98. package/sample-app/prisma/schema.prisma +0 -34
  99. package/sample-app/public/favicon.ico +0 -0
  100. package/sample-app/remix.config.js +0 -10
  101. package/sample-app/remix.env.d.ts +0 -2
@@ -0,0 +1,26 @@
1
+ export type FieldErrors = Record<string, string>;
2
+
3
+ export type GenericObject = { [key: string]: any };
4
+
5
+ /**
6
+ * The result when validating a form.
7
+ */
8
+ export type ValidationResult<DataType> =
9
+ | { data: DataType; error: undefined }
10
+ | { error: FieldErrors; data: undefined };
11
+
12
+ /**
13
+ * The result when validating an individual field in a form.
14
+ */
15
+ export type ValidateFieldResult = { error?: string };
16
+
17
+ /**
18
+ * A `Validator` can be passed to the `validator` prop of a `ValidatedForm`.
19
+ */
20
+ export type Validator<DataType> = {
21
+ validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
22
+ validateField: (
23
+ unvalidatedData: GenericObject,
24
+ field: string
25
+ ) => ValidateFieldResult;
26
+ };
@@ -0,0 +1,317 @@
1
+ import * as yup from "yup";
2
+ import { z } from "zod";
3
+ import { Validator, withYup } from "..";
4
+ import { TestFormData } from "../test-data/testFormData";
5
+ import { withZod } from "./withZod";
6
+
7
+ // If adding an adapter, write a validator that validates this shape
8
+ type Person = {
9
+ firstName: string;
10
+ lastName: string;
11
+ age?: number;
12
+ address: {
13
+ streetAddress: string;
14
+ city: string;
15
+ country: string;
16
+ };
17
+ pets?: {
18
+ animal: string;
19
+ name: string;
20
+ }[];
21
+ };
22
+
23
+ type ValidationTestCase = {
24
+ name: string;
25
+ validator: Validator<Person>;
26
+ };
27
+
28
+ const validationTestCases: ValidationTestCase[] = [
29
+ {
30
+ name: "yup",
31
+ validator: withYup(
32
+ yup.object({
33
+ firstName: yup.string().required(),
34
+ lastName: yup.string().required(),
35
+ age: yup.number(),
36
+ address: yup
37
+ .object({
38
+ streetAddress: yup.string().required(),
39
+ city: yup.string().required(),
40
+ country: yup.string().required(),
41
+ })
42
+ .required(),
43
+ pets: yup.array().of(
44
+ yup.object({
45
+ animal: yup.string().required(),
46
+ name: yup.string().required(),
47
+ })
48
+ ),
49
+ })
50
+ ),
51
+ },
52
+ {
53
+ name: "zod",
54
+ validator: withZod(
55
+ z.object({
56
+ firstName: z.string().nonempty(),
57
+ lastName: z.string().nonempty(),
58
+ age: z.optional(z.number()),
59
+ address: z.preprocess(
60
+ (value) => (value == null ? {} : value),
61
+ z.object({
62
+ streetAddress: z.string().nonempty(),
63
+ city: z.string().nonempty(),
64
+ country: z.string().nonempty(),
65
+ })
66
+ ),
67
+ pets: z
68
+ .object({
69
+ animal: z.string().nonempty(),
70
+ name: z.string().nonempty(),
71
+ })
72
+ .array()
73
+ .optional(),
74
+ })
75
+ ),
76
+ },
77
+ ];
78
+
79
+ // Not going to enforce exact error strings here
80
+ const anyString = expect.any(String);
81
+
82
+ describe("Validation", () => {
83
+ describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
84
+ describe("validate", () => {
85
+ it("should return the data when valid", () => {
86
+ const person: Person = {
87
+ firstName: "John",
88
+ lastName: "Doe",
89
+ age: 30,
90
+ address: {
91
+ streetAddress: "123 Main St",
92
+ city: "Anytown",
93
+ country: "USA",
94
+ },
95
+ pets: [{ animal: "dog", name: "Fido" }],
96
+ };
97
+ expect(validator.validate(person)).toEqual({
98
+ data: person,
99
+ error: undefined,
100
+ });
101
+ });
102
+
103
+ it("should return field errors when invalid", () => {
104
+ const obj = { age: "hi!", pets: [{ animal: "dog" }] };
105
+ expect(validator.validate(obj)).toEqual({
106
+ data: undefined,
107
+ error: {
108
+ firstName: anyString,
109
+ lastName: anyString,
110
+ age: anyString,
111
+ "address.city": anyString,
112
+ "address.country": anyString,
113
+ "address.streetAddress": anyString,
114
+ "pets[0].name": anyString,
115
+ },
116
+ });
117
+ });
118
+
119
+ it("should unflatten data when validating", () => {
120
+ const data = {
121
+ firstName: "John",
122
+ lastName: "Doe",
123
+ age: 30,
124
+ "address.streetAddress": "123 Main St",
125
+ "address.city": "Anytown",
126
+ "address.country": "USA",
127
+ "pets[0].animal": "dog",
128
+ "pets[0].name": "Fido",
129
+ };
130
+ expect(validator.validate(data)).toEqual({
131
+ data: {
132
+ firstName: "John",
133
+ lastName: "Doe",
134
+ age: 30,
135
+ address: {
136
+ streetAddress: "123 Main St",
137
+ city: "Anytown",
138
+ country: "USA",
139
+ },
140
+ pets: [{ animal: "dog", name: "Fido" }],
141
+ },
142
+ error: undefined,
143
+ });
144
+ });
145
+
146
+ it("should accept FormData directly and return errors", () => {
147
+ const formData = new 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("pets[0].animal", "dog");
153
+
154
+ expect(validator.validate(formData)).toEqual({
155
+ data: undefined,
156
+ error: {
157
+ "address.city": anyString,
158
+ "pets[0].name": anyString,
159
+ },
160
+ });
161
+ });
162
+
163
+ it("should accept FormData directly and return valid data", () => {
164
+ const formData = new TestFormData();
165
+ formData.set("firstName", "John");
166
+ formData.set("lastName", "Doe");
167
+ formData.set("address.streetAddress", "123 Main St");
168
+ formData.set("address.country", "USA");
169
+ formData.set("address.city", "Anytown");
170
+ formData.set("pets[0].animal", "dog");
171
+ formData.set("pets[0].name", "Fido");
172
+
173
+ expect(validator.validate(formData)).toEqual({
174
+ data: {
175
+ firstName: "John",
176
+ lastName: "Doe",
177
+ address: {
178
+ streetAddress: "123 Main St",
179
+ country: "USA",
180
+ city: "Anytown",
181
+ },
182
+ pets: [{ animal: "dog", name: "Fido" }],
183
+ },
184
+ error: undefined,
185
+ });
186
+ });
187
+ });
188
+
189
+ describe("validateField", () => {
190
+ it("should not return an error if field is valid", () => {
191
+ const person = {
192
+ firstName: "John",
193
+ lastName: {}, // invalid, but we should only be validating firstName
194
+ };
195
+ expect(validator.validateField(person, "firstName")).toEqual({
196
+ error: undefined,
197
+ });
198
+ });
199
+ it("should not return an error if a nested field is valid", () => {
200
+ const person = {
201
+ firstName: "John",
202
+ lastName: {}, // invalid, but we should only be validating firstName
203
+ address: {
204
+ streetAddress: "123 Main St",
205
+ city: "Anytown",
206
+ country: "USA",
207
+ },
208
+ pets: [{ animal: "dog", name: "Fido" }],
209
+ };
210
+ expect(
211
+ validator.validateField(person, "address.streetAddress")
212
+ ).toEqual({
213
+ error: undefined,
214
+ });
215
+ expect(validator.validateField(person, "address.city")).toEqual({
216
+ error: undefined,
217
+ });
218
+ expect(validator.validateField(person, "address.country")).toEqual({
219
+ error: undefined,
220
+ });
221
+ expect(validator.validateField(person, "pets[0].animal")).toEqual({
222
+ error: undefined,
223
+ });
224
+ expect(validator.validateField(person, "pets[0].name")).toEqual({
225
+ error: undefined,
226
+ });
227
+ });
228
+
229
+ it("should return an error if field is invalid", () => {
230
+ const person = {
231
+ firstName: "John",
232
+ lastName: {},
233
+ address: {
234
+ streetAddress: "123 Main St",
235
+ city: 1234,
236
+ },
237
+ };
238
+ expect(validator.validateField(person, "lastName")).toEqual({
239
+ error: anyString,
240
+ });
241
+ });
242
+
243
+ it("should return an error if a nested field is invalid", () => {
244
+ const person = {
245
+ firstName: "John",
246
+ lastName: {},
247
+ address: {
248
+ streetAddress: "123 Main St",
249
+ city: 1234,
250
+ },
251
+ pets: [{ animal: "dog" }],
252
+ };
253
+ expect(validator.validateField(person, "address.country")).toEqual({
254
+ error: anyString,
255
+ });
256
+ expect(validator.validateField(person, "pets[0].name")).toEqual({
257
+ error: anyString,
258
+ });
259
+ });
260
+ });
261
+ });
262
+ });
263
+
264
+ describe("withZod", () => {
265
+ it("returns coherent errors for complex schemas", () => {
266
+ const schema = z.union([
267
+ z.object({
268
+ type: z.literal("foo"),
269
+ foo: z.string(),
270
+ }),
271
+ z.object({
272
+ type: z.literal("bar"),
273
+ bar: z.string(),
274
+ }),
275
+ ]);
276
+ const obj = {
277
+ type: "foo",
278
+ bar: 123,
279
+ foo: 123,
280
+ };
281
+
282
+ expect(withZod(schema).validate(obj)).toEqual({
283
+ data: undefined,
284
+ error: {
285
+ type: anyString,
286
+ bar: anyString,
287
+ foo: anyString,
288
+ },
289
+ });
290
+ });
291
+
292
+ it("returns errors for fields that are unions", () => {
293
+ const schema = z.object({
294
+ field1: z.union([z.literal("foo"), z.literal("bar")]),
295
+ field2: z.union([z.literal("foo"), z.literal("bar")]),
296
+ });
297
+ const obj = {
298
+ field1: "a value",
299
+ // field2 missing
300
+ };
301
+
302
+ const validator = withZod(schema);
303
+ expect(validator.validate(obj)).toEqual({
304
+ data: undefined,
305
+ error: {
306
+ field1: anyString,
307
+ field2: anyString,
308
+ },
309
+ });
310
+ expect(validator.validateField(obj, "field1")).toEqual({
311
+ error: anyString,
312
+ });
313
+ expect(validator.validateField(obj, "field2")).toEqual({
314
+ error: anyString,
315
+ });
316
+ });
317
+ });
@@ -0,0 +1,43 @@
1
+ import type { AnyObjectSchema, InferType, ValidationError } from "yup";
2
+ import { createValidator } from "./createValidator";
3
+ import { FieldErrors, Validator } from "./types";
4
+
5
+ const validationErrorToFieldErrors = (error: ValidationError): FieldErrors => {
6
+ const fieldErrors: FieldErrors = {};
7
+ error.inner.forEach((innerError) => {
8
+ if (!innerError.path) return;
9
+ fieldErrors[innerError.path] = innerError.message;
10
+ });
11
+ return fieldErrors;
12
+ };
13
+
14
+ /**
15
+ * Create a `Validator` using a `yup` schema.
16
+ */
17
+ export const withYup = <Schema extends AnyObjectSchema>(
18
+ validationSchema: Schema
19
+ ): Validator<InferType<Schema>> => {
20
+ return createValidator({
21
+ validate: (data) => {
22
+ try {
23
+ const validated = validationSchema.validateSync(data, {
24
+ abortEarly: false,
25
+ });
26
+ return { data: validated, error: undefined };
27
+ } catch (err) {
28
+ return {
29
+ error: validationErrorToFieldErrors(err as ValidationError),
30
+ data: undefined,
31
+ };
32
+ }
33
+ },
34
+ validateField: (data, field) => {
35
+ try {
36
+ validationSchema.validateSyncAt(field, data);
37
+ return {};
38
+ } catch (err) {
39
+ return { error: (err as ValidationError).message };
40
+ }
41
+ },
42
+ });
43
+ };
@@ -0,0 +1,51 @@
1
+ import isEqual from "lodash/isEqual";
2
+ import toPath from "lodash/toPath";
3
+ import type { z } from "zod";
4
+ import { FieldErrors, Validator } from "..";
5
+ import { createValidator } from "./createValidator";
6
+
7
+ const getIssuesForError = (err: z.ZodError<any>): z.ZodIssue[] => {
8
+ return err.issues.flatMap((issue) => {
9
+ if ("unionErrors" in issue) {
10
+ return issue.unionErrors.flatMap((err) => getIssuesForError(err));
11
+ } else {
12
+ return [issue];
13
+ }
14
+ });
15
+ };
16
+
17
+ function pathToString(array: (string | number)[]): string {
18
+ return array.reduce(function (string: string, item: string | number) {
19
+ var prefix = string === "" ? "" : ".";
20
+ return string + (isNaN(Number(item)) ? prefix + item : "[" + item + "]");
21
+ }, "");
22
+ }
23
+
24
+ /**
25
+ * Create a validator using a `zod` schema.
26
+ */
27
+ export function withZod<T>(zodSchema: z.Schema<T>): Validator<T> {
28
+ return createValidator({
29
+ validate: (value) => {
30
+ const result = zodSchema.safeParse(value);
31
+ if (result.success) return { data: result.data, error: undefined };
32
+
33
+ const fieldErrors: FieldErrors = {};
34
+ getIssuesForError(result.error).forEach((issue) => {
35
+ const path = pathToString(issue.path);
36
+ if (!fieldErrors[path]) fieldErrors[path] = issue.message;
37
+ });
38
+ return { error: fieldErrors, data: undefined };
39
+ },
40
+ validateField: (data, field) => {
41
+ const result = zodSchema.safeParse(data);
42
+ if (result.success) return { error: undefined };
43
+ return {
44
+ error: getIssuesForError(result.error).find((issue) => {
45
+ const allPathsAsString = issue.path.map((p) => `${p}`);
46
+ return isEqual(allPathsAsString, toPath(field));
47
+ })?.message,
48
+ };
49
+ },
50
+ });
51
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "tsconfig/tsconfig.json",
3
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
4
+ "exclude": ["node_modules"]
5
+ }
package/.eslintcache DELETED
@@ -1 +0,0 @@
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/.eslintignore DELETED
@@ -1 +0,0 @@
1
- ./package-lock.json
package/.prettierignore DELETED
@@ -1,10 +0,0 @@
1
- .cache
2
- build
3
- browser
4
- test-app/build
5
- test-app/remix-validated-form
6
- sample-app/build
7
- sample-app/remix-validated-form
8
- node_modules
9
- public
10
- package-lock.json
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2021 Aaron Pettengill
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.