remix-validated-form 2.1.1 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  $ npm run build:browser && npm run build:main
2
2
 
3
- > remix-validated-form@2.1.0 build:browser
3
+ > remix-validated-form@2.1.1 build:browser
4
4
  > tsc --module ESNext --outDir ./browser
5
5
 
6
6
 
7
- > remix-validated-form@2.1.0 build:main
7
+ > remix-validated-form@2.1.1 build:main
8
8
  > tsc --module CommonJS --outDir ./build
9
9
 
@@ -2,7 +2,5 @@ export * from "./hooks";
2
2
  export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
- export * from "./validation/withYup";
6
- export * from "./validation/withZod";
7
5
  export * from "./validation/createValidator";
8
6
  export type { FormContextValue } from "./internal/formContext";
package/browser/index.js CHANGED
@@ -2,6 +2,4 @@ export * from "./hooks";
2
2
  export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
- export * from "./validation/withYup";
6
- export * from "./validation/withZod";
7
5
  export * from "./validation/createValidator";
package/build/index.d.ts CHANGED
@@ -2,7 +2,5 @@ export * from "./hooks";
2
2
  export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
- export * from "./validation/withYup";
6
- export * from "./validation/withZod";
7
5
  export * from "./validation/createValidator";
8
6
  export type { FormContextValue } from "./internal/formContext";
package/build/index.js CHANGED
@@ -14,6 +14,4 @@ __exportStar(require("./hooks"), exports);
14
14
  __exportStar(require("./server"), exports);
15
15
  __exportStar(require("./ValidatedForm"), exports);
16
16
  __exportStar(require("./validation/types"), exports);
17
- __exportStar(require("./validation/withYup"), exports);
18
- __exportStar(require("./validation/withZod"), exports);
19
17
  __exportStar(require("./validation/createValidator"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remix-validated-form",
3
- "version": "2.1.1",
3
+ "version": "3.0.0-beta.1",
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",
@@ -31,6 +31,7 @@
31
31
  "react",
32
32
  "form",
33
33
  "yup",
34
+ "zod",
34
35
  "validation"
35
36
  ],
36
37
  "peerDependencies": {
@@ -41,16 +42,12 @@
41
42
  "devDependencies": {
42
43
  "@remix-run/react": "^1.0.6",
43
44
  "@remix-run/server-runtime": "^1.0.6",
44
- "@types/jest": "^27.0.3",
45
45
  "@types/lodash": "^4.14.178",
46
46
  "@types/react": "^17.0.37",
47
47
  "fetch-blob": "^3.1.3",
48
48
  "react": "^17.0.2",
49
- "ts-jest": "^27.1.1",
50
49
  "tsconfig": "*",
51
- "typescript": "^4.5.3",
52
- "yup": "^0.32.11",
53
- "zod": "^3.11.6"
50
+ "typescript": "^4.5.3"
54
51
  },
55
52
  "dependencies": {
56
53
  "lodash": "^4.17.21",
package/src/index.ts CHANGED
@@ -2,7 +2,5 @@ export * from "./hooks";
2
2
  export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
- export * from "./validation/withYup";
6
- export * from "./validation/withZod";
7
5
  export * from "./validation/createValidator";
8
6
  export type { FormContextValue } from "./internal/formContext";
package/jest.config.js DELETED
@@ -1,10 +0,0 @@
1
- /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
2
- module.exports = {
3
- globals: {
4
- "ts-jest": {
5
- tsconfig: "tsconfig.json",
6
- },
7
- },
8
- preset: "ts-jest",
9
- testEnvironment: "node",
10
- };
@@ -1,55 +0,0 @@
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 implements FormData {
4
- private _params: URLSearchParams;
5
-
6
- constructor(body?: string) {
7
- this._params = new URLSearchParams(body);
8
- }
9
- append(name: string, value: string | Blob, fileName?: string): void {
10
- if (typeof value !== "string") {
11
- throw new Error("formData.append can only accept a string");
12
- }
13
- this._params.append(name, value);
14
- }
15
- delete(name: string): void {
16
- this._params.delete(name);
17
- }
18
- get(name: string): FormDataEntryValue | null {
19
- return this._params.get(name);
20
- }
21
- getAll(name: string): FormDataEntryValue[] {
22
- return this._params.getAll(name);
23
- }
24
- has(name: string): boolean {
25
- return this._params.has(name);
26
- }
27
- set(name: string, value: string | Blob, fileName?: string): void {
28
- if (typeof value !== "string") {
29
- throw new Error("formData.set can only accept a string");
30
- }
31
- this._params.set(name, value);
32
- }
33
- forEach(
34
- callbackfn: (
35
- value: FormDataEntryValue,
36
- key: string,
37
- parent: FormData
38
- ) => void,
39
- thisArg?: any
40
- ): void {
41
- this._params.forEach(callbackfn, thisArg);
42
- }
43
- entries(): IterableIterator<[string, FormDataEntryValue]> {
44
- return this._params.entries();
45
- }
46
- keys(): IterableIterator<string> {
47
- return this._params.keys();
48
- }
49
- values(): IterableIterator<FormDataEntryValue> {
50
- return this._params.values();
51
- }
52
- *[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]> {
53
- yield* this._params;
54
- }
55
- }
@@ -1,322 +0,0 @@
1
- import * as yup from "yup";
2
- import { z } from "zod";
3
- import { Validator, withYup } from "..";
4
- import { objectFromPathEntries } from "../internal/flatten";
5
- import { TestFormData } from "../test-data/testFormData";
6
- import { withZod } from "./withZod";
7
-
8
- // If adding an adapter, write a validator that validates this shape
9
- type Person = {
10
- firstName: string;
11
- lastName: string;
12
- age?: number;
13
- address: {
14
- streetAddress: string;
15
- city: string;
16
- country: string;
17
- };
18
- pets?: {
19
- animal: string;
20
- name: string;
21
- }[];
22
- };
23
-
24
- type ValidationTestCase = {
25
- name: string;
26
- validator: Validator<Person>;
27
- };
28
-
29
- const validationTestCases: ValidationTestCase[] = [
30
- {
31
- name: "yup",
32
- validator: withYup(
33
- yup.object({
34
- firstName: yup.string().required(),
35
- lastName: yup.string().required(),
36
- age: yup.number(),
37
- address: yup
38
- .object({
39
- streetAddress: yup.string().required(),
40
- city: yup.string().required(),
41
- country: yup.string().required(),
42
- })
43
- .required(),
44
- pets: yup.array().of(
45
- yup.object({
46
- animal: yup.string().required(),
47
- name: yup.string().required(),
48
- })
49
- ),
50
- })
51
- ),
52
- },
53
- {
54
- name: "zod",
55
- validator: withZod(
56
- z.object({
57
- firstName: z.string().nonempty(),
58
- lastName: z.string().nonempty(),
59
- age: z.optional(z.number()),
60
- address: z.preprocess(
61
- (value) => (value == null ? {} : value),
62
- z.object({
63
- streetAddress: z.string().nonempty(),
64
- city: z.string().nonempty(),
65
- country: z.string().nonempty(),
66
- })
67
- ),
68
- pets: z
69
- .object({
70
- animal: z.string().nonempty(),
71
- name: z.string().nonempty(),
72
- })
73
- .array()
74
- .optional(),
75
- })
76
- ),
77
- },
78
- ];
79
-
80
- // Not going to enforce exact error strings here
81
- const anyString = expect.any(String);
82
-
83
- describe("Validation", () => {
84
- describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
85
- describe("validate", () => {
86
- it("should return the data when valid", () => {
87
- const person: Person = {
88
- firstName: "John",
89
- lastName: "Doe",
90
- age: 30,
91
- address: {
92
- streetAddress: "123 Main St",
93
- city: "Anytown",
94
- country: "USA",
95
- },
96
- pets: [{ animal: "dog", name: "Fido" }],
97
- };
98
- expect(validator.validate(person)).toEqual({
99
- data: person,
100
- error: undefined,
101
- });
102
- });
103
-
104
- it("should return field errors when invalid", () => {
105
- const obj = { age: "hi!", pets: [{ animal: "dog" }] };
106
- expect(validator.validate(obj)).toEqual({
107
- data: undefined,
108
- error: {
109
- firstName: anyString,
110
- lastName: anyString,
111
- age: anyString,
112
- "address.city": anyString,
113
- "address.country": anyString,
114
- "address.streetAddress": anyString,
115
- "pets[0].name": anyString,
116
- _submittedData: obj,
117
- },
118
- });
119
- });
120
-
121
- it("should unflatten data when validating", () => {
122
- const data = {
123
- firstName: "John",
124
- lastName: "Doe",
125
- age: 30,
126
- "address.streetAddress": "123 Main St",
127
- "address.city": "Anytown",
128
- "address.country": "USA",
129
- "pets[0].animal": "dog",
130
- "pets[0].name": "Fido",
131
- };
132
- expect(validator.validate(data)).toEqual({
133
- data: {
134
- firstName: "John",
135
- lastName: "Doe",
136
- age: 30,
137
- address: {
138
- streetAddress: "123 Main St",
139
- city: "Anytown",
140
- country: "USA",
141
- },
142
- pets: [{ animal: "dog", name: "Fido" }],
143
- },
144
- error: undefined,
145
- });
146
- });
147
-
148
- it("should accept FormData directly and return errors", () => {
149
- const formData = new TestFormData();
150
- formData.set("firstName", "John");
151
- formData.set("lastName", "Doe");
152
- formData.set("address.streetAddress", "123 Main St");
153
- formData.set("address.country", "USA");
154
- formData.set("pets[0].animal", "dog");
155
-
156
- expect(validator.validate(formData)).toEqual({
157
- data: undefined,
158
- error: {
159
- "address.city": anyString,
160
- "pets[0].name": anyString,
161
- _submittedData: objectFromPathEntries([...formData.entries()]),
162
- },
163
- });
164
- });
165
-
166
- it("should accept FormData directly and return valid data", () => {
167
- const formData = new TestFormData();
168
- formData.set("firstName", "John");
169
- formData.set("lastName", "Doe");
170
- formData.set("address.streetAddress", "123 Main St");
171
- formData.set("address.country", "USA");
172
- formData.set("address.city", "Anytown");
173
- formData.set("pets[0].animal", "dog");
174
- formData.set("pets[0].name", "Fido");
175
-
176
- expect(validator.validate(formData)).toEqual({
177
- data: {
178
- firstName: "John",
179
- lastName: "Doe",
180
- address: {
181
- streetAddress: "123 Main St",
182
- country: "USA",
183
- city: "Anytown",
184
- },
185
- pets: [{ animal: "dog", name: "Fido" }],
186
- },
187
- error: undefined,
188
- });
189
- });
190
- });
191
-
192
- describe("validateField", () => {
193
- it("should not return an error if field is valid", () => {
194
- const person = {
195
- firstName: "John",
196
- lastName: {}, // invalid, but we should only be validating firstName
197
- };
198
- expect(validator.validateField(person, "firstName")).toEqual({
199
- error: undefined,
200
- });
201
- });
202
- it("should not return an error if a nested field is valid", () => {
203
- const person = {
204
- firstName: "John",
205
- lastName: {}, // invalid, but we should only be validating firstName
206
- address: {
207
- streetAddress: "123 Main St",
208
- city: "Anytown",
209
- country: "USA",
210
- },
211
- pets: [{ animal: "dog", name: "Fido" }],
212
- };
213
- expect(
214
- validator.validateField(person, "address.streetAddress")
215
- ).toEqual({
216
- error: undefined,
217
- });
218
- expect(validator.validateField(person, "address.city")).toEqual({
219
- error: undefined,
220
- });
221
- expect(validator.validateField(person, "address.country")).toEqual({
222
- error: undefined,
223
- });
224
- expect(validator.validateField(person, "pets[0].animal")).toEqual({
225
- error: undefined,
226
- });
227
- expect(validator.validateField(person, "pets[0].name")).toEqual({
228
- error: undefined,
229
- });
230
- });
231
-
232
- it("should return an error if field is invalid", () => {
233
- const person = {
234
- firstName: "John",
235
- lastName: {},
236
- address: {
237
- streetAddress: "123 Main St",
238
- city: 1234,
239
- },
240
- };
241
- expect(validator.validateField(person, "lastName")).toEqual({
242
- error: anyString,
243
- });
244
- });
245
-
246
- it("should return an error if a nested field is invalid", () => {
247
- const person = {
248
- firstName: "John",
249
- lastName: {},
250
- address: {
251
- streetAddress: "123 Main St",
252
- city: 1234,
253
- },
254
- pets: [{ animal: "dog" }],
255
- };
256
- expect(validator.validateField(person, "address.country")).toEqual({
257
- error: anyString,
258
- });
259
- expect(validator.validateField(person, "pets[0].name")).toEqual({
260
- error: anyString,
261
- });
262
- });
263
- });
264
- });
265
- });
266
-
267
- describe("withZod", () => {
268
- it("returns coherent errors for complex schemas", () => {
269
- const schema = z.union([
270
- z.object({
271
- type: z.literal("foo"),
272
- foo: z.string(),
273
- }),
274
- z.object({
275
- type: z.literal("bar"),
276
- bar: z.string(),
277
- }),
278
- ]);
279
- const obj = {
280
- type: "foo",
281
- bar: 123,
282
- foo: 123,
283
- };
284
-
285
- expect(withZod(schema).validate(obj)).toEqual({
286
- data: undefined,
287
- error: {
288
- type: anyString,
289
- bar: anyString,
290
- foo: anyString,
291
- _submittedData: obj,
292
- },
293
- });
294
- });
295
-
296
- it("returns errors for fields that are unions", () => {
297
- const schema = z.object({
298
- field1: z.union([z.literal("foo"), z.literal("bar")]),
299
- field2: z.union([z.literal("foo"), z.literal("bar")]),
300
- });
301
- const obj = {
302
- field1: "a value",
303
- // field2 missing
304
- };
305
-
306
- const validator = withZod(schema);
307
- expect(validator.validate(obj)).toEqual({
308
- data: undefined,
309
- error: {
310
- field1: anyString,
311
- field2: anyString,
312
- _submittedData: obj,
313
- },
314
- });
315
- expect(validator.validateField(obj, "field1")).toEqual({
316
- error: anyString,
317
- });
318
- expect(validator.validateField(obj, "field2")).toEqual({
319
- error: anyString,
320
- });
321
- });
322
- });
@@ -1,43 +0,0 @@
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
- };
@@ -1,51 +0,0 @@
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
- }