remix-validated-form 0.0.3 → 1.1.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/.eslintcache +1 -0
- package/.prettierignore +2 -0
- package/README.md +228 -1
- package/browser/ValidatedForm.js +1 -1
- package/browser/flatten.d.ts +5 -0
- package/browser/flatten.js +41 -0
- package/browser/hooks.js +5 -1
- package/browser/index.d.ts +1 -0
- package/browser/index.js +1 -0
- package/browser/server.d.ts +1 -1
- package/browser/server.js +1 -1
- package/browser/validation/createValidator.d.ts +3 -0
- package/browser/validation/createValidator.js +8 -0
- package/browser/validation/types.d.ts +5 -2
- package/browser/validation/validation.test.js +156 -8
- package/browser/validation/withYup.js +28 -25
- package/browser/validation/withZod.d.ts +3 -0
- package/browser/validation/withZod.js +47 -0
- package/build/ValidatedForm.js +1 -1
- package/build/flatten.d.ts +5 -0
- package/build/flatten.js +49 -0
- package/build/hooks.js +8 -1
- package/build/index.d.ts +1 -0
- package/build/index.js +1 -0
- package/build/server.d.ts +1 -1
- package/build/server.js +3 -3
- package/build/validation/createValidator.d.ts +3 -0
- package/build/validation/createValidator.js +12 -0
- package/build/validation/types.d.ts +5 -2
- package/build/validation/validation.test.js +156 -8
- package/build/validation/withYup.js +28 -25
- package/build/validation/withZod.d.ts +3 -0
- package/build/validation/withZod.js +54 -0
- package/package.json +20 -14
- package/sample-app/.env +7 -0
- package/sample-app/README.md +53 -0
- package/sample-app/app/components/ErrorBox.tsx +34 -0
- package/sample-app/app/components/FormInput.tsx +40 -0
- package/sample-app/app/components/FormSelect.tsx +37 -0
- package/sample-app/app/components/SubjectForm.tsx +150 -0
- package/sample-app/app/entry.client.tsx +4 -0
- package/sample-app/app/entry.server.tsx +21 -0
- package/sample-app/app/root.tsx +92 -0
- package/sample-app/app/routes/index.tsx +5 -0
- package/sample-app/app/routes/subjects/$id.edit.tsx +100 -0
- package/sample-app/app/routes/subjects/index.tsx +112 -0
- package/sample-app/app/routes/subjects/new.tsx +48 -0
- package/sample-app/app/services/db.server.ts +23 -0
- package/sample-app/app/types.ts +6 -0
- package/sample-app/package-lock.json +4617 -0
- package/sample-app/package.json +36 -0
- package/sample-app/prisma/dev.db +0 -0
- package/sample-app/prisma/schema.prisma +34 -0
- package/sample-app/public/favicon.ico +0 -0
- package/sample-app/remix.config.js +10 -0
- package/sample-app/remix.env.d.ts +2 -0
package/.eslintcache
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
[{"/Users/aaronpettengill/dev/remix-validated-form/src/server.ts":"1","/Users/aaronpettengill/dev/remix-validated-form/src/validation/types.ts":"2","/Users/aaronpettengill/dev/remix-validated-form/src/validation/withYup.ts":"3","/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx":"4","/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation-fetcher.tsx":"5","/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation-with-fetchers.ts":"6","/Users/aaronpettengill/dev/remix-validated-form/src/validation/validation.test.ts":"7","/Users/aaronpettengill/dev/remix-validated-form/src/validation/withZod.ts":"8","/Users/aaronpettengill/dev/remix-validated-form/src/index.ts":"9","/Users/aaronpettengill/dev/remix-validated-form/src/ValidatedForm.tsx":"10"},{"size":207,"mtime":1637876506168,"results":"11","hashOfConfig":"12"},{"size":438,"mtime":1637877226360,"results":"13","hashOfConfig":"12"},{"size":1085,"mtime":1637877476573,"results":"14","hashOfConfig":"12"},{"size":1293,"mtime":1637876566355,"results":"15","hashOfConfig":"12"},{"size":1330,"mtime":1637902697212,"results":"16","hashOfConfig":"12"},{"size":2220,"mtime":1637902736281,"results":"17","hashOfConfig":"12"},{"size":3526,"mtime":1638155421909,"results":"18","hashOfConfig":"12"},{"size":1168,"mtime":1638155747107,"results":"19","hashOfConfig":"12"},{"size":196,"mtime":1638159719317,"results":"20","hashOfConfig":"12"},{"size":3478,"mtime":1638498151067,"results":"21","hashOfConfig":"12"},{"filePath":"22","messages":"23","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"bt07le",{"filePath":"24","messages":"25","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"26","messages":"27","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"28","messages":"29","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"30","messages":"31","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"32","messages":"33","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"34","messages":"35","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"36","messages":"37","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"38","messages":"39","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"40","messages":"41","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/aaronpettengill/dev/remix-validated-form/src/server.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/types.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/withYup.ts",["42"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx",[],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation-fetcher.tsx",["43"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/cypress/integration/validation-with-fetchers.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/validation.test.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/validation/withZod.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/index.ts",[],"/Users/aaronpettengill/dev/remix-validated-form/src/ValidatedForm.tsx",[],{"ruleId":"44","severity":1,"message":"45","line":2,"column":23,"nodeType":"46","messageId":"47","endLine":2,"endColumn":39},{"ruleId":"44","severity":1,"message":"48","line":1,"column":26,"nodeType":"46","messageId":"47","endLine":1,"endColumn":39},"@typescript-eslint/no-unused-vars","'ValidationResult' is defined but never used.","Identifier","unusedVar","'useActionData' is defined but never used."]
|
package/.prettierignore
CHANGED
package/README.md
CHANGED
@@ -1,3 +1,230 @@
|
|
1
1
|
# Remix Validated Form
|
2
2
|
|
3
|
-
A form library built for [remix](https://remix.run).
|
3
|
+
A form library built for [remix](https://remix.run) to make validation easy.
|
4
|
+
|
5
|
+
- Client-side, field-by-field validation (e.g. validate on blur) and form-level validation
|
6
|
+
- Set default values for the entire form in one place
|
7
|
+
- Re-use validation on the server
|
8
|
+
- Show validation errors from the server even without JS
|
9
|
+
- Detect if the current form is submitting when there are multiple forms on the page
|
10
|
+
- Supports nested objects and arrays
|
11
|
+
- Validation library agnostic
|
12
|
+
|
13
|
+
# Demo
|
14
|
+
|
15
|
+
https://user-images.githubusercontent.com/2811287/145734901-700a5085-a10b-4d89-88e1-5de9142b1e85.mov
|
16
|
+
|
17
|
+
To run `sample-app`:
|
18
|
+
```
|
19
|
+
git clone https://github.com/airjp73/remix-validated-form
|
20
|
+
cd remix-validated-form
|
21
|
+
npm i
|
22
|
+
cd sample-app
|
23
|
+
npm i
|
24
|
+
cd ..
|
25
|
+
npm run sample-app
|
26
|
+
```
|
27
|
+
|
28
|
+
# Getting started
|
29
|
+
|
30
|
+
## Install
|
31
|
+
|
32
|
+
```bash
|
33
|
+
npm install remix-validated-form
|
34
|
+
```
|
35
|
+
|
36
|
+
## Create an input component
|
37
|
+
|
38
|
+
In order to display field errors or do field-by-field validation,
|
39
|
+
it's recommended to incorporate this library into an input component using `useField`.
|
40
|
+
|
41
|
+
```tsx
|
42
|
+
import { useField } from "remix-validated-form";
|
43
|
+
|
44
|
+
type MyInputProps = {
|
45
|
+
name: string;
|
46
|
+
label: string;
|
47
|
+
};
|
48
|
+
|
49
|
+
export const MyInput = ({ name, label }: InputProps) => {
|
50
|
+
const { validate, clearError, defaultValue, error } = useField(name);
|
51
|
+
return (
|
52
|
+
<div>
|
53
|
+
<label htmlFor={name}>{label}</label>
|
54
|
+
<input
|
55
|
+
id={name}
|
56
|
+
name={name}
|
57
|
+
onBlur={validate}
|
58
|
+
onChange={clearError}
|
59
|
+
defaultValue={defaultValue}
|
60
|
+
/>
|
61
|
+
{error && <span className="my-error-class">{error}</span>}
|
62
|
+
</div>
|
63
|
+
);
|
64
|
+
};
|
65
|
+
```
|
66
|
+
|
67
|
+
## Create a submit button component
|
68
|
+
|
69
|
+
To best take advantage of the per-form submission detection, we can create a submit button component.
|
70
|
+
|
71
|
+
```tsx
|
72
|
+
import { useIsSubmitting } from "remix-validated-form";
|
73
|
+
|
74
|
+
export const MySubmitButton = () => {
|
75
|
+
const isSubmitting = useIsSubmitting();
|
76
|
+
return (
|
77
|
+
<button type="submit" disabled={isSubmitting}>
|
78
|
+
{isSubmitting ? "Submitting..." : "Submit"}
|
79
|
+
</button>
|
80
|
+
);
|
81
|
+
};
|
82
|
+
```
|
83
|
+
|
84
|
+
## Use the form!
|
85
|
+
|
86
|
+
Now that we have our components, making a form is easy!
|
87
|
+
|
88
|
+
```tsx
|
89
|
+
import { ActionFunction, LoaderFunction, redirect, useLoaderData } from "remix";
|
90
|
+
import * as yup from "yup";
|
91
|
+
import { validationError, ValidatedForm, withYup } from "remix-validated-form";
|
92
|
+
import { MyInput, MySubmitButton } from "~/components/Input";
|
93
|
+
|
94
|
+
// Using yup in this example, but you can use anything
|
95
|
+
const validator = withYup(
|
96
|
+
yup.object({
|
97
|
+
firstName: yup.string().label("First Name").required(),
|
98
|
+
lastName: yup.string().label("Last Name").required(),
|
99
|
+
email: yup.string().email().label("Email").required(),
|
100
|
+
})
|
101
|
+
);
|
102
|
+
|
103
|
+
export const action: ActionFunction = async ({ request }) => {
|
104
|
+
const fieldValues = validator.validate(
|
105
|
+
Object.fromEntries(await request.formData())
|
106
|
+
);
|
107
|
+
if (fieldValues.error) return validationError(fieldValues.error);
|
108
|
+
const { firstName, lastName, email } = fieldValues.data;
|
109
|
+
|
110
|
+
// Do something with correctly typed values;
|
111
|
+
|
112
|
+
return redirect("/");
|
113
|
+
};
|
114
|
+
|
115
|
+
export const loader: LoaderFunction = () => {
|
116
|
+
return {
|
117
|
+
defaultValues: {
|
118
|
+
firstName: "Jane",
|
119
|
+
lastName: "Doe",
|
120
|
+
email: "jane.doe@example.com",
|
121
|
+
},
|
122
|
+
};
|
123
|
+
};
|
124
|
+
|
125
|
+
export default function MyForm() {
|
126
|
+
const { defaultValues } = useLoaderData();
|
127
|
+
return (
|
128
|
+
<ValidatedForm
|
129
|
+
validator={validator}
|
130
|
+
method="post"
|
131
|
+
defaultValues={defaultValues}
|
132
|
+
>
|
133
|
+
<MyInput name="firstName" label="First Name" />
|
134
|
+
<MyInput name="lastName" label="Last Name" />
|
135
|
+
<MyInput name="email" label="Email" />
|
136
|
+
<MySubmitButton />
|
137
|
+
</ValidatedForm>
|
138
|
+
);
|
139
|
+
}
|
140
|
+
```
|
141
|
+
|
142
|
+
## Nested objects and arrays
|
143
|
+
|
144
|
+
You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
|
145
|
+
|
146
|
+
```tsx
|
147
|
+
export default function MyForm() {
|
148
|
+
const { defaultValues } = useLoaderData();
|
149
|
+
return (
|
150
|
+
<ValidatedForm
|
151
|
+
validator={validator}
|
152
|
+
method="post"
|
153
|
+
defaultValues={defaultValues}
|
154
|
+
>
|
155
|
+
<MyInput name="firstName" label="First Name" />
|
156
|
+
<MyInput name="lastName" label="Last Name" />
|
157
|
+
<MyInput name="address.street" label="Street" />
|
158
|
+
<MyInput name="address.city" label="City" />
|
159
|
+
<MyInput name="phones[0].type" label="Phone 1 Type" />
|
160
|
+
<MyInput name="phones[0].number" label="Phone 1 Number" />
|
161
|
+
<MyInput name="phones[1].type" label="Phone 2 Type" />
|
162
|
+
<MyInput name="phones[1].number" label="Phone 2 Number" />
|
163
|
+
<MySubmitButton />
|
164
|
+
</ValidatedForm>
|
165
|
+
);
|
166
|
+
}
|
167
|
+
```
|
168
|
+
|
169
|
+
# Validation Library Support
|
170
|
+
|
171
|
+
This library currently includes an out-of-the-box adapter for `yup` and `zod`,
|
172
|
+
but you can easily support whatever library you want by creating your own adapter.
|
173
|
+
|
174
|
+
And if you create an adapter for a library, feel free to make a PR on this library to add official support 😊
|
175
|
+
|
176
|
+
## Creating an adapter
|
177
|
+
|
178
|
+
Any object that conforms to the `Validator` type can be passed into the the `ValidatedForm`'s `validator` prop.
|
179
|
+
|
180
|
+
```ts
|
181
|
+
type FieldErrors = Record<string, string>;
|
182
|
+
|
183
|
+
type ValidationResult<DataType> =
|
184
|
+
| { data: DataType; error: undefined }
|
185
|
+
| { error: FieldErrors; data: undefined };
|
186
|
+
|
187
|
+
type ValidateFieldResult = { error?: string };
|
188
|
+
|
189
|
+
type Validator<DataType> = {
|
190
|
+
validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
|
191
|
+
validateField: (
|
192
|
+
unvalidatedData: unknown,
|
193
|
+
field: string
|
194
|
+
) => ValidateFieldResult;
|
195
|
+
};
|
196
|
+
```
|
197
|
+
|
198
|
+
In order to make an adapter for your validation library of choice,
|
199
|
+
you can create a function that accepts a schema from the validation library and turns it into a validator.
|
200
|
+
|
201
|
+
Note the use of `createValidator`. It takes care of unflatten the data for nested objects and arrays since the form doesn't know anything about object and arrays and this should be handled by the adapter. For more on this you can check the implementations for `withZod` and `withYup`.
|
202
|
+
|
203
|
+
The out-of-the-box support for `yup` in this library works like this:
|
204
|
+
|
205
|
+
```ts
|
206
|
+
export const withYup = <Schema extends AnyObjectSchema>(
|
207
|
+
validationSchema: Schema
|
208
|
+
// For best result with Typescript, we should type the `Validator` we return based on the provided schema
|
209
|
+
): Validator<InferType<Schema>> => createValidator({
|
210
|
+
validate: (unvalidatedData) => {
|
211
|
+
// Validate with yup and return the validated & typed data or the error
|
212
|
+
|
213
|
+
if (isValid) return { data: { field1: "someValue" }, error: undefined };
|
214
|
+
else return { error: { field1: "Some error!" }, data: undefined };
|
215
|
+
},
|
216
|
+
validateField: (unvalidatedData, field) => {
|
217
|
+
// Validate the specific field with yup
|
218
|
+
|
219
|
+
if (isValid) return { error: undefined };
|
220
|
+
else return { error: "Some error" };
|
221
|
+
},
|
222
|
+
});
|
223
|
+
```
|
224
|
+
|
225
|
+
# Frequenty Asked Questions
|
226
|
+
|
227
|
+
## Why are my fields triggering the native HTML validations before `remix-validated-form` ones?
|
228
|
+
This is happening because you or the library you are using are passing the `required` attribute to the fields. This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors. If you wan't to disable all native HTML validations you can add `noValidate` to `<ValidatedForm>`. We recommend this approach since the validation will still work even if JS is disabled.
|
229
|
+
|
230
|
+
|
package/browser/ValidatedForm.js
CHANGED
@@ -21,7 +21,7 @@ const useIsSubmitting = (action, fetcher) => {
|
|
21
21
|
return fetcher
|
22
22
|
? fetcher.state === "submitting"
|
23
23
|
: pendingFormSubmit &&
|
24
|
-
pendingFormSubmit.action
|
24
|
+
pendingFormSubmit.action === (action !== null && action !== void 0 ? action : actionForCurrentPage);
|
25
25
|
};
|
26
26
|
const getDataFromForm = (el) => Object.fromEntries(new FormData(el));
|
27
27
|
export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
|
@@ -0,0 +1,5 @@
|
|
1
|
+
import { GenericObject } from ".";
|
2
|
+
/** Unflatten a previously flatten object */
|
3
|
+
export declare function unflatten(params: GenericObject): {};
|
4
|
+
/** Flatten an object so there are no nested objects or arrays */
|
5
|
+
export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
|
@@ -0,0 +1,41 @@
|
|
1
|
+
// `flatten` and `unflatten` are 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 reduce from "lodash/reduce";
|
8
|
+
import set from "lodash/set";
|
9
|
+
import transform from "lodash/transform";
|
10
|
+
/** Unflatten a previously flatten object */
|
11
|
+
export function unflatten(params) {
|
12
|
+
return reduce(params, function (result, value, key) {
|
13
|
+
return set(result, key, value);
|
14
|
+
}, {});
|
15
|
+
}
|
16
|
+
/** Flatten an object so there are no nested objects or arrays */
|
17
|
+
export function flatten(obj, preserveEmpty = false) {
|
18
|
+
return transform(obj, function (result, value, key) {
|
19
|
+
if (isObject(value)) {
|
20
|
+
let flatMap = mapKeys(flatten(value, preserveEmpty), function (_mvalue, mkey) {
|
21
|
+
if (isArray(value)) {
|
22
|
+
let index = mkey.indexOf(".");
|
23
|
+
if (-1 !== index) {
|
24
|
+
return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
|
25
|
+
}
|
26
|
+
return `${key}[${mkey}]`;
|
27
|
+
}
|
28
|
+
return `${key}.${mkey}`;
|
29
|
+
});
|
30
|
+
assign(result, flatMap);
|
31
|
+
// Preverve Empty arrays and objects
|
32
|
+
if (preserveEmpty && keys(flatMap).length === 0) {
|
33
|
+
result[key] = value;
|
34
|
+
}
|
35
|
+
}
|
36
|
+
else {
|
37
|
+
result[key] = value;
|
38
|
+
}
|
39
|
+
return result;
|
40
|
+
}, {});
|
41
|
+
}
|
package/browser/hooks.js
CHANGED
@@ -1,3 +1,5 @@
|
|
1
|
+
import get from "lodash/get";
|
2
|
+
import toPath from "lodash/toPath";
|
1
3
|
import { useContext, useMemo } from "react";
|
2
4
|
import { FormContext } from "./internal/formContext";
|
3
5
|
export const useField = (name) => {
|
@@ -8,7 +10,9 @@ export const useField = (name) => {
|
|
8
10
|
clearError(name);
|
9
11
|
},
|
10
12
|
validate: () => validateField(name),
|
11
|
-
defaultValue: defaultValues
|
13
|
+
defaultValue: defaultValues
|
14
|
+
? get(defaultValues, toPath(name), undefined)
|
15
|
+
: undefined,
|
12
16
|
}), [clearError, defaultValues, fieldErrors, name, validateField]);
|
13
17
|
return field;
|
14
18
|
};
|
package/browser/index.d.ts
CHANGED
package/browser/index.js
CHANGED
package/browser/server.d.ts
CHANGED
@@ -1,2 +1,2 @@
|
|
1
1
|
import { FieldErrors } from "./validation/types";
|
2
|
-
export declare const
|
2
|
+
export declare const validationError: (errors: FieldErrors) => Response;
|
package/browser/server.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
1
|
import { json } from "@remix-run/server-runtime";
|
2
|
-
export const
|
2
|
+
export const validationError = (errors) => json({ fieldErrors: errors }, { status: 422 });
|
@@ -0,0 +1,8 @@
|
|
1
|
+
import { unflatten } from "../flatten";
|
2
|
+
/** Handles data manipulation such us flattening the data to send to the validator */
|
3
|
+
export function createValidator(validator) {
|
4
|
+
return {
|
5
|
+
validate: (value) => validator.validate(unflatten(value)),
|
6
|
+
validateField: (data, field) => validator.validateField(unflatten(data), field),
|
7
|
+
};
|
8
|
+
}
|
@@ -1,4 +1,7 @@
|
|
1
1
|
export declare type FieldErrors = Record<string, string>;
|
2
|
+
export declare type GenericObject = {
|
3
|
+
[key: string]: any;
|
4
|
+
};
|
2
5
|
export declare type ValidationResult<DataType> = {
|
3
6
|
data: DataType;
|
4
7
|
error: undefined;
|
@@ -10,6 +13,6 @@ export declare type ValidateFieldResult = {
|
|
10
13
|
error?: string;
|
11
14
|
};
|
12
15
|
export declare type Validator<DataType> = {
|
13
|
-
validate: (
|
14
|
-
validateField: (
|
16
|
+
validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
|
17
|
+
validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
|
15
18
|
};
|
@@ -1,5 +1,7 @@
|
|
1
1
|
import * as yup from "yup";
|
2
|
+
import { z } from "zod";
|
2
3
|
import { withYup } from "..";
|
4
|
+
import { withZod } from "./withZod";
|
3
5
|
const validationTestCases = [
|
4
6
|
{
|
5
7
|
name: "yup",
|
@@ -7,6 +9,37 @@ const validationTestCases = [
|
|
7
9
|
firstName: yup.string().required(),
|
8
10
|
lastName: yup.string().required(),
|
9
11
|
age: yup.number(),
|
12
|
+
address: yup
|
13
|
+
.object({
|
14
|
+
streetAddress: yup.string().required(),
|
15
|
+
city: yup.string().required(),
|
16
|
+
country: yup.string().required(),
|
17
|
+
})
|
18
|
+
.required(),
|
19
|
+
pets: yup.array().of(yup.object({
|
20
|
+
animal: yup.string().required(),
|
21
|
+
name: yup.string().required(),
|
22
|
+
})),
|
23
|
+
})),
|
24
|
+
},
|
25
|
+
{
|
26
|
+
name: "zod",
|
27
|
+
validator: withZod(z.object({
|
28
|
+
firstName: z.string().nonempty(),
|
29
|
+
lastName: z.string().nonempty(),
|
30
|
+
age: z.optional(z.number()),
|
31
|
+
address: z.preprocess((value) => (value == null ? {} : value), z.object({
|
32
|
+
streetAddress: z.string().nonempty(),
|
33
|
+
city: z.string().nonempty(),
|
34
|
+
country: z.string().nonempty(),
|
35
|
+
})),
|
36
|
+
pets: z
|
37
|
+
.object({
|
38
|
+
animal: z.string().nonempty(),
|
39
|
+
name: z.string().nonempty(),
|
40
|
+
})
|
41
|
+
.array()
|
42
|
+
.optional(),
|
10
43
|
})),
|
11
44
|
},
|
12
45
|
];
|
@@ -16,41 +49,156 @@ describe("Validation", () => {
|
|
16
49
|
describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
|
17
50
|
describe("validate", () => {
|
18
51
|
it("should return the data when valid", () => {
|
19
|
-
const
|
52
|
+
const person = {
|
20
53
|
firstName: "John",
|
21
54
|
lastName: "Doe",
|
22
55
|
age: 30,
|
56
|
+
address: {
|
57
|
+
streetAddress: "123 Main St",
|
58
|
+
city: "Anytown",
|
59
|
+
country: "USA",
|
60
|
+
},
|
61
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
23
62
|
};
|
24
|
-
expect(validator.validate(
|
25
|
-
data:
|
63
|
+
expect(validator.validate(person)).toEqual({
|
64
|
+
data: person,
|
26
65
|
error: undefined,
|
27
66
|
});
|
28
67
|
});
|
29
68
|
it("should return field errors when invalid", () => {
|
30
|
-
const obj = { age: "hi!" };
|
69
|
+
const obj = { age: "hi!", pets: [{ animal: "dog" }] };
|
31
70
|
expect(validator.validate(obj)).toEqual({
|
32
71
|
data: undefined,
|
33
72
|
error: {
|
34
73
|
firstName: anyString,
|
35
74
|
lastName: anyString,
|
36
75
|
age: anyString,
|
76
|
+
"address.city": anyString,
|
77
|
+
"address.country": anyString,
|
78
|
+
"address.streetAddress": anyString,
|
79
|
+
"pets[0].name": anyString,
|
37
80
|
},
|
38
81
|
});
|
39
82
|
});
|
40
83
|
});
|
41
84
|
describe("validateField", () => {
|
42
85
|
it("should not return an error if field is valid", () => {
|
43
|
-
const
|
44
|
-
|
86
|
+
const person = {
|
87
|
+
firstName: "John",
|
88
|
+
lastName: {}, // invalid, but we should only be validating firstName
|
89
|
+
};
|
90
|
+
expect(validator.validateField(person, "firstName")).toEqual({
|
91
|
+
error: undefined,
|
92
|
+
});
|
93
|
+
});
|
94
|
+
it("should not return an error if a nested field is valid", () => {
|
95
|
+
const person = {
|
96
|
+
firstName: "John",
|
97
|
+
lastName: {},
|
98
|
+
address: {
|
99
|
+
streetAddress: "123 Main St",
|
100
|
+
city: "Anytown",
|
101
|
+
country: "USA",
|
102
|
+
},
|
103
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
104
|
+
};
|
105
|
+
expect(validator.validateField(person, "address.streetAddress")).toEqual({
|
106
|
+
error: undefined,
|
107
|
+
});
|
108
|
+
expect(validator.validateField(person, "address.city")).toEqual({
|
109
|
+
error: undefined,
|
110
|
+
});
|
111
|
+
expect(validator.validateField(person, "address.country")).toEqual({
|
112
|
+
error: undefined,
|
113
|
+
});
|
114
|
+
expect(validator.validateField(person, "pets[0].animal")).toEqual({
|
115
|
+
error: undefined,
|
116
|
+
});
|
117
|
+
expect(validator.validateField(person, "pets[0].name")).toEqual({
|
45
118
|
error: undefined,
|
46
119
|
});
|
47
120
|
});
|
48
121
|
it("should return an error if field is invalid", () => {
|
49
|
-
const
|
50
|
-
|
122
|
+
const person = {
|
123
|
+
firstName: "John",
|
124
|
+
lastName: {},
|
125
|
+
address: {
|
126
|
+
streetAddress: "123 Main St",
|
127
|
+
city: 1234,
|
128
|
+
},
|
129
|
+
};
|
130
|
+
expect(validator.validateField(person, "lastName")).toEqual({
|
131
|
+
error: anyString,
|
132
|
+
});
|
133
|
+
});
|
134
|
+
it("should return an error if a nested field is invalid", () => {
|
135
|
+
const person = {
|
136
|
+
firstName: "John",
|
137
|
+
lastName: {},
|
138
|
+
address: {
|
139
|
+
streetAddress: "123 Main St",
|
140
|
+
city: 1234,
|
141
|
+
},
|
142
|
+
pets: [{ animal: "dog" }],
|
143
|
+
};
|
144
|
+
expect(validator.validateField(person, "address.country")).toEqual({
|
145
|
+
error: anyString,
|
146
|
+
});
|
147
|
+
expect(validator.validateField(person, "pets[0].name")).toEqual({
|
51
148
|
error: anyString,
|
52
149
|
});
|
53
150
|
});
|
54
151
|
});
|
55
152
|
});
|
56
153
|
});
|
154
|
+
describe("withZod", () => {
|
155
|
+
it("returns coherent errors for complex schemas", () => {
|
156
|
+
const schema = z.union([
|
157
|
+
z.object({
|
158
|
+
type: z.literal("foo"),
|
159
|
+
foo: z.string(),
|
160
|
+
}),
|
161
|
+
z.object({
|
162
|
+
type: z.literal("bar"),
|
163
|
+
bar: z.string(),
|
164
|
+
}),
|
165
|
+
]);
|
166
|
+
const obj = {
|
167
|
+
type: "foo",
|
168
|
+
bar: 123,
|
169
|
+
foo: 123,
|
170
|
+
};
|
171
|
+
expect(withZod(schema).validate(obj)).toEqual({
|
172
|
+
data: undefined,
|
173
|
+
error: {
|
174
|
+
type: anyString,
|
175
|
+
bar: anyString,
|
176
|
+
foo: anyString,
|
177
|
+
},
|
178
|
+
});
|
179
|
+
});
|
180
|
+
it("returns errors for fields that are unions", () => {
|
181
|
+
const schema = z.object({
|
182
|
+
field1: z.union([z.literal("foo"), z.literal("bar")]),
|
183
|
+
field2: z.union([z.literal("foo"), z.literal("bar")]),
|
184
|
+
});
|
185
|
+
const obj = {
|
186
|
+
field1: "a value",
|
187
|
+
// field2 missing
|
188
|
+
};
|
189
|
+
const validator = withZod(schema);
|
190
|
+
expect(validator.validate(obj)).toEqual({
|
191
|
+
data: undefined,
|
192
|
+
error: {
|
193
|
+
field1: anyString,
|
194
|
+
field2: anyString,
|
195
|
+
},
|
196
|
+
});
|
197
|
+
expect(validator.validateField(obj, "field1")).toEqual({
|
198
|
+
error: anyString,
|
199
|
+
});
|
200
|
+
expect(validator.validateField(obj, "field2")).toEqual({
|
201
|
+
error: anyString,
|
202
|
+
});
|
203
|
+
});
|
204
|
+
});
|
@@ -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,30 @@ const validationErrorToFieldErrors = (error) => {
|
|
7
8
|
});
|
8
9
|
return fieldErrors;
|
9
10
|
};
|
10
|
-
export const withYup = (validationSchema) =>
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
}
|
11
|
+
export const withYup = (validationSchema) => {
|
12
|
+
return createValidator({
|
13
|
+
validate: (data) => {
|
14
|
+
try {
|
15
|
+
const validated = validationSchema.validateSync(data, {
|
16
|
+
abortEarly: false,
|
17
|
+
});
|
18
|
+
return { data: validated, error: undefined };
|
19
|
+
}
|
20
|
+
catch (err) {
|
21
|
+
return {
|
22
|
+
error: validationErrorToFieldErrors(err),
|
23
|
+
data: undefined,
|
24
|
+
};
|
25
|
+
}
|
26
|
+
},
|
27
|
+
validateField: (data, field) => {
|
28
|
+
try {
|
29
|
+
validationSchema.validateSyncAt(field, data);
|
30
|
+
return {};
|
31
|
+
}
|
32
|
+
catch (err) {
|
33
|
+
return { error: err.message };
|
34
|
+
}
|
35
|
+
},
|
36
|
+
});
|
37
|
+
};
|