remix-validated-form 2.0.1-beta.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +9 -0
- package/.turbo/turbo-dev.log +0 -0
- package/.turbo/turbo-test.log +10 -35
- package/README.md +20 -8
- package/browser/ValidatedForm.d.ts +13 -1
- package/browser/ValidatedForm.js +72 -19
- package/browser/index.d.ts +0 -2
- package/browser/index.js +0 -2
- package/browser/internal/submissionCallbacks.d.ts +1 -0
- package/browser/internal/submissionCallbacks.js +13 -0
- package/browser/validation/createValidator.js +12 -1
- package/browser/validation/types.d.ts +3 -0
- package/browser/validation/validation.test.js +5 -0
- package/build/ValidatedForm.d.ts +13 -1
- package/build/ValidatedForm.js +71 -18
- package/build/index.d.ts +0 -2
- package/build/index.js +0 -2
- package/build/internal/submissionCallbacks.d.ts +1 -0
- package/build/internal/submissionCallbacks.js +17 -0
- package/build/validation/createValidator.js +12 -1
- package/build/validation/types.d.ts +3 -0
- package/package.json +4 -9
- package/src/ValidatedForm.tsx +96 -18
- package/src/index.ts +0 -2
- package/src/internal/submissionCallbacks.ts +15 -0
- package/src/validation/createValidator.ts +12 -2
- package/src/validation/types.ts +2 -0
- package/build/test-data/testFormData.d.ts +0 -15
- package/build/test-data/testFormData.js +0 -50
- package/build/validation/validation.test.d.ts +0 -1
- package/build/validation/validation.test.js +0 -290
- package/build/validation/withYup.d.ts +0 -6
- package/build/validation/withYup.js +0 -44
- package/build/validation/withZod.d.ts +0 -6
- package/build/validation/withZod.js +0 -57
- package/jest.config.js +0 -10
- package/src/test-data/testFormData.ts +0 -55
- package/src/validation/validation.test.ts +0 -317
- package/src/validation/withYup.ts +0 -43
- package/src/validation/withZod.ts +0 -51
package/src/ValidatedForm.tsx
CHANGED
@@ -14,8 +14,13 @@ import React, {
|
|
14
14
|
} from "react";
|
15
15
|
import invariant from "tiny-invariant";
|
16
16
|
import { FormContext, FormContextValue } from "./internal/formContext";
|
17
|
+
import { useSubmitComplete } from "./internal/submissionCallbacks";
|
17
18
|
import { omit, mergeRefs } from "./internal/util";
|
18
|
-
import {
|
19
|
+
import {
|
20
|
+
FieldErrors,
|
21
|
+
Validator,
|
22
|
+
FieldErrorsWithData,
|
23
|
+
} from "./validation/types";
|
19
24
|
|
20
25
|
export type FormProps<DataType> = {
|
21
26
|
/**
|
@@ -42,39 +47,95 @@ export type FormProps<DataType> = {
|
|
42
47
|
* A ref to the form element.
|
43
48
|
*/
|
44
49
|
formRef?: React.RefObject<HTMLFormElement>;
|
50
|
+
/**
|
51
|
+
* An optional sub-action to use for the form.
|
52
|
+
* Setting a value here will cause the form to be submitted with an extra `subaction` value.
|
53
|
+
* This can be useful when there are multiple forms on the screen handled by the same action.
|
54
|
+
*/
|
55
|
+
subaction?: string;
|
56
|
+
/**
|
57
|
+
* Reset the form to the default values after the form has been successfully submitted.
|
58
|
+
* This is useful if you want to submit the same form multiple times,
|
59
|
+
* and don't redirect in-between submissions.
|
60
|
+
*/
|
61
|
+
resetAfterSubmit?: boolean;
|
45
62
|
} & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
|
46
63
|
|
47
|
-
function
|
48
|
-
fetcher?: ReturnType<typeof useFetcher
|
49
|
-
|
64
|
+
function useFieldErrorsFromBackend(
|
65
|
+
fetcher?: ReturnType<typeof useFetcher>,
|
66
|
+
subaction?: string
|
67
|
+
): FieldErrorsWithData | null {
|
50
68
|
const actionData = useActionData<any>();
|
51
|
-
|
52
|
-
|
69
|
+
if (fetcher) return (fetcher.data as any)?.fieldErrors;
|
70
|
+
if (!actionData) return null;
|
71
|
+
if (actionData.fieldErrors) {
|
72
|
+
const submittedData = actionData.fieldErrors?._submittedData;
|
73
|
+
const subactionsMatch = subaction
|
74
|
+
? subaction === submittedData?.subaction
|
75
|
+
: !submittedData?.subaction;
|
76
|
+
return subactionsMatch ? actionData.fieldErrors : null;
|
77
|
+
}
|
78
|
+
return null;
|
79
|
+
}
|
53
80
|
|
81
|
+
function useFieldErrors(
|
82
|
+
fieldErrorsFromBackend?: any
|
83
|
+
): [FieldErrors, React.Dispatch<React.SetStateAction<FieldErrors>>] {
|
54
84
|
const [fieldErrors, setFieldErrors] = useState<FieldErrors>(
|
55
|
-
|
85
|
+
fieldErrorsFromBackend ?? {}
|
56
86
|
);
|
57
87
|
useEffect(() => {
|
58
|
-
if (
|
59
|
-
}, [
|
88
|
+
if (fieldErrorsFromBackend) setFieldErrors(fieldErrorsFromBackend);
|
89
|
+
}, [fieldErrorsFromBackend]);
|
60
90
|
|
61
91
|
return [fieldErrors, setFieldErrors];
|
62
92
|
}
|
63
93
|
|
64
94
|
const useIsSubmitting = (
|
65
95
|
action?: string,
|
96
|
+
subaction?: string,
|
66
97
|
fetcher?: ReturnType<typeof useFetcher>
|
67
98
|
) => {
|
68
99
|
const actionForCurrentPage = useFormAction();
|
69
100
|
const pendingFormSubmit = useTransition().submission;
|
70
|
-
|
71
|
-
|
72
|
-
|
73
|
-
|
101
|
+
|
102
|
+
if (fetcher) return fetcher.state === "submitting";
|
103
|
+
if (!pendingFormSubmit) return false;
|
104
|
+
|
105
|
+
const { formData, action: pendingAction } = pendingFormSubmit;
|
106
|
+
const pendingSubAction = formData.get("subaction");
|
107
|
+
const expectedAction = action ?? actionForCurrentPage;
|
108
|
+
if (subaction)
|
109
|
+
return expectedAction === pendingAction && subaction === pendingSubAction;
|
110
|
+
return expectedAction === pendingAction && !pendingSubAction;
|
74
111
|
};
|
75
112
|
|
76
113
|
const getDataFromForm = (el: HTMLFormElement) => new FormData(el);
|
77
114
|
|
115
|
+
/**
|
116
|
+
* The purpose for this logic is to handle validation errors when javascript is disabled.
|
117
|
+
* Normally (without js), when a form is submitted and the action returns the validation errors,
|
118
|
+
* the form will be reset. The errors will be displayed on the correct fields,
|
119
|
+
* but all the values in the form will be gone. This is not good UX.
|
120
|
+
*
|
121
|
+
* To get around this, we return the submitted form data from the server,
|
122
|
+
* and use those to populate the form via `defaultValues`.
|
123
|
+
* This results in a more seamless UX akin to what you would see when js is enabled.
|
124
|
+
*
|
125
|
+
* One potential downside is that resetting the form will reset the form
|
126
|
+
* to the _new_ default values that were returned from the server with the validation errors.
|
127
|
+
* However, this case is less of a problem than the janky UX caused by losing the form values.
|
128
|
+
* It will only ever be a problem if the form includes a `<button type="reset" />`
|
129
|
+
* and only if JS is disabled.
|
130
|
+
*/
|
131
|
+
function useDefaultValues<DataType>(
|
132
|
+
fieldErrors?: FieldErrorsWithData | null,
|
133
|
+
defaultValues?: Partial<DataType>
|
134
|
+
) {
|
135
|
+
const defaultsFromValidationError = fieldErrors?._submittedData;
|
136
|
+
return defaultsFromValidationError ?? defaultValues;
|
137
|
+
}
|
138
|
+
|
78
139
|
/**
|
79
140
|
* The primary form component of `remix-validated-form`.
|
80
141
|
*/
|
@@ -86,18 +147,27 @@ export function ValidatedForm<DataType>({
|
|
86
147
|
action,
|
87
148
|
defaultValues,
|
88
149
|
formRef: formRefProp,
|
150
|
+
onReset,
|
151
|
+
subaction,
|
152
|
+
resetAfterSubmit,
|
89
153
|
...rest
|
90
154
|
}: FormProps<DataType>) {
|
91
|
-
const
|
92
|
-
const
|
93
|
-
|
155
|
+
const fieldErrorsFromBackend = useFieldErrorsFromBackend(fetcher, subaction);
|
156
|
+
const [fieldErrors, setFieldErrors] = useFieldErrors(fieldErrorsFromBackend);
|
157
|
+
const isSubmitting = useIsSubmitting(action, subaction, fetcher);
|
158
|
+
const defaultsToUse = useDefaultValues(fieldErrorsFromBackend, defaultValues);
|
94
159
|
const formRef = useRef<HTMLFormElement>(null);
|
160
|
+
useSubmitComplete(isSubmitting, () => {
|
161
|
+
if (!fieldErrorsFromBackend && resetAfterSubmit) {
|
162
|
+
formRef.current?.reset();
|
163
|
+
}
|
164
|
+
});
|
95
165
|
|
96
166
|
const contextValue = useMemo<FormContextValue>(
|
97
167
|
() => ({
|
98
168
|
fieldErrors,
|
99
169
|
action,
|
100
|
-
defaultValues,
|
170
|
+
defaultValues: defaultsToUse,
|
101
171
|
isSubmitting: isSubmitting ?? false,
|
102
172
|
clearError: (fieldName) => {
|
103
173
|
setFieldErrors((prev) => omit(prev, fieldName));
|
@@ -119,7 +189,7 @@ export function ValidatedForm<DataType>({
|
|
119
189
|
[
|
120
190
|
fieldErrors,
|
121
191
|
action,
|
122
|
-
|
192
|
+
defaultsToUse,
|
123
193
|
isSubmitting,
|
124
194
|
setFieldErrors,
|
125
195
|
validator,
|
@@ -142,8 +212,16 @@ export function ValidatedForm<DataType>({
|
|
142
212
|
onSubmit?.(result.data, event);
|
143
213
|
}
|
144
214
|
}}
|
215
|
+
onReset={(event) => {
|
216
|
+
onReset?.(event);
|
217
|
+
if (event.defaultPrevented) return;
|
218
|
+
setFieldErrors({});
|
219
|
+
}}
|
145
220
|
>
|
146
221
|
<FormContext.Provider value={contextValue}>
|
222
|
+
{subaction && (
|
223
|
+
<input type="hidden" value={subaction} name="subaction" />
|
224
|
+
)}
|
147
225
|
{children}
|
148
226
|
</FormContext.Provider>
|
149
227
|
</Form>
|
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";
|
@@ -0,0 +1,15 @@
|
|
1
|
+
import { useEffect, useRef } from "react";
|
2
|
+
|
3
|
+
export function useSubmitComplete(isSubmitting: boolean, callback: () => void) {
|
4
|
+
const isPending = useRef(false);
|
5
|
+
useEffect(() => {
|
6
|
+
if (isSubmitting) {
|
7
|
+
isPending.current = true;
|
8
|
+
}
|
9
|
+
|
10
|
+
if (!isSubmitting && isPending.current) {
|
11
|
+
isPending.current = false;
|
12
|
+
callback();
|
13
|
+
}
|
14
|
+
});
|
15
|
+
}
|
@@ -16,8 +16,18 @@ const preprocessFormData = (data: GenericObject | FormData): GenericObject => {
|
|
16
16
|
*/
|
17
17
|
export function createValidator<T>(validator: Validator<T>): Validator<T> {
|
18
18
|
return {
|
19
|
-
validate: (value: GenericObject | FormData) =>
|
20
|
-
|
19
|
+
validate: (value: GenericObject | FormData) => {
|
20
|
+
const data = preprocessFormData(value);
|
21
|
+
const result = validator.validate(data);
|
22
|
+
if (result.error) {
|
23
|
+
// Ideally, we should probably be returning a nested object like
|
24
|
+
// { fieldErrors: {}, submittedData: {} }
|
25
|
+
// We should do this in the next major version of the library
|
26
|
+
// but for now, we can sneak it in with the fieldErrors.
|
27
|
+
result.error._submittedData = data as any;
|
28
|
+
}
|
29
|
+
return result;
|
30
|
+
},
|
21
31
|
validateField: (data: GenericObject | FormData, field: string) =>
|
22
32
|
validator.validateField(preprocessFormData(data), field),
|
23
33
|
};
|
package/src/validation/types.ts
CHANGED
@@ -1,15 +0,0 @@
|
|
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
|
-
}
|
@@ -1,50 +0,0 @@
|
|
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 +0,0 @@
|
|
1
|
-
export {};
|
@@ -1,290 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3
|
-
if (k2 === undefined) k2 = k;
|
4
|
-
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
5
|
-
}) : (function(o, m, k, k2) {
|
6
|
-
if (k2 === undefined) k2 = k;
|
7
|
-
o[k2] = m[k];
|
8
|
-
}));
|
9
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
10
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
11
|
-
}) : function(o, v) {
|
12
|
-
o["default"] = v;
|
13
|
-
});
|
14
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
15
|
-
if (mod && mod.__esModule) return mod;
|
16
|
-
var result = {};
|
17
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
18
|
-
__setModuleDefault(result, mod);
|
19
|
-
return result;
|
20
|
-
};
|
21
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
22
|
-
const yup = __importStar(require("yup"));
|
23
|
-
const zod_1 = require("zod");
|
24
|
-
const __1 = require("..");
|
25
|
-
const testFormData_1 = require("../test-data/testFormData");
|
26
|
-
const withZod_1 = require("./withZod");
|
27
|
-
const validationTestCases = [
|
28
|
-
{
|
29
|
-
name: "yup",
|
30
|
-
validator: (0, __1.withYup)(yup.object({
|
31
|
-
firstName: yup.string().required(),
|
32
|
-
lastName: yup.string().required(),
|
33
|
-
age: yup.number(),
|
34
|
-
address: yup
|
35
|
-
.object({
|
36
|
-
streetAddress: yup.string().required(),
|
37
|
-
city: yup.string().required(),
|
38
|
-
country: yup.string().required(),
|
39
|
-
})
|
40
|
-
.required(),
|
41
|
-
pets: yup.array().of(yup.object({
|
42
|
-
animal: yup.string().required(),
|
43
|
-
name: yup.string().required(),
|
44
|
-
})),
|
45
|
-
})),
|
46
|
-
},
|
47
|
-
{
|
48
|
-
name: "zod",
|
49
|
-
validator: (0, withZod_1.withZod)(zod_1.z.object({
|
50
|
-
firstName: zod_1.z.string().nonempty(),
|
51
|
-
lastName: zod_1.z.string().nonempty(),
|
52
|
-
age: zod_1.z.optional(zod_1.z.number()),
|
53
|
-
address: zod_1.z.preprocess((value) => (value == null ? {} : value), zod_1.z.object({
|
54
|
-
streetAddress: zod_1.z.string().nonempty(),
|
55
|
-
city: zod_1.z.string().nonempty(),
|
56
|
-
country: zod_1.z.string().nonempty(),
|
57
|
-
})),
|
58
|
-
pets: zod_1.z
|
59
|
-
.object({
|
60
|
-
animal: zod_1.z.string().nonempty(),
|
61
|
-
name: zod_1.z.string().nonempty(),
|
62
|
-
})
|
63
|
-
.array()
|
64
|
-
.optional(),
|
65
|
-
})),
|
66
|
-
},
|
67
|
-
];
|
68
|
-
// Not going to enforce exact error strings here
|
69
|
-
const anyString = expect.any(String);
|
70
|
-
describe("Validation", () => {
|
71
|
-
describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
|
72
|
-
describe("validate", () => {
|
73
|
-
it("should return the data when valid", () => {
|
74
|
-
const person = {
|
75
|
-
firstName: "John",
|
76
|
-
lastName: "Doe",
|
77
|
-
age: 30,
|
78
|
-
address: {
|
79
|
-
streetAddress: "123 Main St",
|
80
|
-
city: "Anytown",
|
81
|
-
country: "USA",
|
82
|
-
},
|
83
|
-
pets: [{ animal: "dog", name: "Fido" }],
|
84
|
-
};
|
85
|
-
expect(validator.validate(person)).toEqual({
|
86
|
-
data: person,
|
87
|
-
error: undefined,
|
88
|
-
});
|
89
|
-
});
|
90
|
-
it("should return field errors when invalid", () => {
|
91
|
-
const obj = { age: "hi!", pets: [{ animal: "dog" }] };
|
92
|
-
expect(validator.validate(obj)).toEqual({
|
93
|
-
data: undefined,
|
94
|
-
error: {
|
95
|
-
firstName: anyString,
|
96
|
-
lastName: anyString,
|
97
|
-
age: anyString,
|
98
|
-
"address.city": anyString,
|
99
|
-
"address.country": anyString,
|
100
|
-
"address.streetAddress": anyString,
|
101
|
-
"pets[0].name": anyString,
|
102
|
-
},
|
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
|
-
});
|
169
|
-
});
|
170
|
-
describe("validateField", () => {
|
171
|
-
it("should not return an error if field is valid", () => {
|
172
|
-
const person = {
|
173
|
-
firstName: "John",
|
174
|
-
lastName: {}, // invalid, but we should only be validating firstName
|
175
|
-
};
|
176
|
-
expect(validator.validateField(person, "firstName")).toEqual({
|
177
|
-
error: undefined,
|
178
|
-
});
|
179
|
-
});
|
180
|
-
it("should not return an error if a nested field is valid", () => {
|
181
|
-
const person = {
|
182
|
-
firstName: "John",
|
183
|
-
lastName: {},
|
184
|
-
address: {
|
185
|
-
streetAddress: "123 Main St",
|
186
|
-
city: "Anytown",
|
187
|
-
country: "USA",
|
188
|
-
},
|
189
|
-
pets: [{ animal: "dog", name: "Fido" }],
|
190
|
-
};
|
191
|
-
expect(validator.validateField(person, "address.streetAddress")).toEqual({
|
192
|
-
error: undefined,
|
193
|
-
});
|
194
|
-
expect(validator.validateField(person, "address.city")).toEqual({
|
195
|
-
error: undefined,
|
196
|
-
});
|
197
|
-
expect(validator.validateField(person, "address.country")).toEqual({
|
198
|
-
error: undefined,
|
199
|
-
});
|
200
|
-
expect(validator.validateField(person, "pets[0].animal")).toEqual({
|
201
|
-
error: undefined,
|
202
|
-
});
|
203
|
-
expect(validator.validateField(person, "pets[0].name")).toEqual({
|
204
|
-
error: undefined,
|
205
|
-
});
|
206
|
-
});
|
207
|
-
it("should return an error if field is invalid", () => {
|
208
|
-
const person = {
|
209
|
-
firstName: "John",
|
210
|
-
lastName: {},
|
211
|
-
address: {
|
212
|
-
streetAddress: "123 Main St",
|
213
|
-
city: 1234,
|
214
|
-
},
|
215
|
-
};
|
216
|
-
expect(validator.validateField(person, "lastName")).toEqual({
|
217
|
-
error: anyString,
|
218
|
-
});
|
219
|
-
});
|
220
|
-
it("should return an error if a nested field is invalid", () => {
|
221
|
-
const person = {
|
222
|
-
firstName: "John",
|
223
|
-
lastName: {},
|
224
|
-
address: {
|
225
|
-
streetAddress: "123 Main St",
|
226
|
-
city: 1234,
|
227
|
-
},
|
228
|
-
pets: [{ animal: "dog" }],
|
229
|
-
};
|
230
|
-
expect(validator.validateField(person, "address.country")).toEqual({
|
231
|
-
error: anyString,
|
232
|
-
});
|
233
|
-
expect(validator.validateField(person, "pets[0].name")).toEqual({
|
234
|
-
error: anyString,
|
235
|
-
});
|
236
|
-
});
|
237
|
-
});
|
238
|
-
});
|
239
|
-
});
|
240
|
-
describe("withZod", () => {
|
241
|
-
it("returns coherent errors for complex schemas", () => {
|
242
|
-
const schema = zod_1.z.union([
|
243
|
-
zod_1.z.object({
|
244
|
-
type: zod_1.z.literal("foo"),
|
245
|
-
foo: zod_1.z.string(),
|
246
|
-
}),
|
247
|
-
zod_1.z.object({
|
248
|
-
type: zod_1.z.literal("bar"),
|
249
|
-
bar: zod_1.z.string(),
|
250
|
-
}),
|
251
|
-
]);
|
252
|
-
const obj = {
|
253
|
-
type: "foo",
|
254
|
-
bar: 123,
|
255
|
-
foo: 123,
|
256
|
-
};
|
257
|
-
expect((0, withZod_1.withZod)(schema).validate(obj)).toEqual({
|
258
|
-
data: undefined,
|
259
|
-
error: {
|
260
|
-
type: anyString,
|
261
|
-
bar: anyString,
|
262
|
-
foo: anyString,
|
263
|
-
},
|
264
|
-
});
|
265
|
-
});
|
266
|
-
it("returns errors for fields that are unions", () => {
|
267
|
-
const schema = zod_1.z.object({
|
268
|
-
field1: zod_1.z.union([zod_1.z.literal("foo"), zod_1.z.literal("bar")]),
|
269
|
-
field2: zod_1.z.union([zod_1.z.literal("foo"), zod_1.z.literal("bar")]),
|
270
|
-
});
|
271
|
-
const obj = {
|
272
|
-
field1: "a value",
|
273
|
-
// field2 missing
|
274
|
-
};
|
275
|
-
const validator = (0, withZod_1.withZod)(schema);
|
276
|
-
expect(validator.validate(obj)).toEqual({
|
277
|
-
data: undefined,
|
278
|
-
error: {
|
279
|
-
field1: anyString,
|
280
|
-
field2: anyString,
|
281
|
-
},
|
282
|
-
});
|
283
|
-
expect(validator.validateField(obj, "field1")).toEqual({
|
284
|
-
error: anyString,
|
285
|
-
});
|
286
|
-
expect(validator.validateField(obj, "field2")).toEqual({
|
287
|
-
error: anyString,
|
288
|
-
});
|
289
|
-
});
|
290
|
-
});
|
@@ -1,6 +0,0 @@
|
|
1
|
-
import type { AnyObjectSchema, InferType } from "yup";
|
2
|
-
import { Validator } from "./types";
|
3
|
-
/**
|
4
|
-
* Create a `Validator` using a `yup` schema.
|
5
|
-
*/
|
6
|
-
export declare const withYup: <Schema extends AnyObjectSchema>(validationSchema: Schema) => Validator<InferType<Schema>>;
|
@@ -1,44 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.withYup = void 0;
|
4
|
-
const createValidator_1 = require("./createValidator");
|
5
|
-
const validationErrorToFieldErrors = (error) => {
|
6
|
-
const fieldErrors = {};
|
7
|
-
error.inner.forEach((innerError) => {
|
8
|
-
if (!innerError.path)
|
9
|
-
return;
|
10
|
-
fieldErrors[innerError.path] = innerError.message;
|
11
|
-
});
|
12
|
-
return fieldErrors;
|
13
|
-
};
|
14
|
-
/**
|
15
|
-
* Create a `Validator` using a `yup` schema.
|
16
|
-
*/
|
17
|
-
const withYup = (validationSchema) => {
|
18
|
-
return (0, createValidator_1.createValidator)({
|
19
|
-
validate: (data) => {
|
20
|
-
try {
|
21
|
-
const validated = validationSchema.validateSync(data, {
|
22
|
-
abortEarly: false,
|
23
|
-
});
|
24
|
-
return { data: validated, error: undefined };
|
25
|
-
}
|
26
|
-
catch (err) {
|
27
|
-
return {
|
28
|
-
error: validationErrorToFieldErrors(err),
|
29
|
-
data: undefined,
|
30
|
-
};
|
31
|
-
}
|
32
|
-
},
|
33
|
-
validateField: (data, field) => {
|
34
|
-
try {
|
35
|
-
validationSchema.validateSyncAt(field, data);
|
36
|
-
return {};
|
37
|
-
}
|
38
|
-
catch (err) {
|
39
|
-
return { error: err.message };
|
40
|
-
}
|
41
|
-
},
|
42
|
-
});
|
43
|
-
};
|
44
|
-
exports.withYup = withYup;
|