remix-validated-form 0.0.2 → 1.1.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 (90) hide show
  1. package/.eslintcache +1 -0
  2. package/README.md +180 -1
  3. package/browser/ValidatedForm.d.ts +11 -0
  4. package/browser/ValidatedForm.js +69 -0
  5. package/browser/hooks.d.ts +8 -0
  6. package/browser/hooks.js +17 -0
  7. package/{src/index.ts → browser/index.d.ts} +0 -0
  8. package/browser/index.js +5 -0
  9. package/browser/internal/formContext.d.ts +13 -0
  10. package/browser/internal/formContext.js +7 -0
  11. package/browser/internal/util.d.ts +3 -0
  12. package/browser/internal/util.js +19 -0
  13. package/browser/server.d.ts +2 -0
  14. package/browser/server.js +2 -0
  15. package/browser/validation/types.d.ts +15 -0
  16. package/browser/validation/types.js +1 -0
  17. package/browser/validation/validation.test.d.ts +1 -0
  18. package/browser/validation/validation.test.js +120 -0
  19. package/browser/validation/withYup.d.ts +3 -0
  20. package/browser/validation/withYup.js +34 -0
  21. package/browser/validation/withZod.d.ts +3 -0
  22. package/browser/validation/withZod.js +35 -0
  23. package/build/ValidatedForm.d.ts +11 -0
  24. package/build/ValidatedForm.js +76 -0
  25. package/build/hooks.d.ts +8 -0
  26. package/build/hooks.js +23 -0
  27. package/build/index.d.ts +5 -0
  28. package/build/index.js +17 -0
  29. package/build/internal/formContext.d.ts +13 -0
  30. package/build/internal/formContext.js +10 -0
  31. package/build/internal/util.d.ts +3 -0
  32. package/build/internal/util.js +24 -0
  33. package/build/server.d.ts +2 -0
  34. package/build/server.js +6 -0
  35. package/build/validation/types.d.ts +15 -0
  36. package/build/validation/types.js +2 -0
  37. package/build/validation/validation.test.d.ts +1 -0
  38. package/build/validation/validation.test.js +141 -0
  39. package/build/validation/withYup.d.ts +3 -0
  40. package/build/validation/withYup.js +38 -0
  41. package/build/validation/withZod.d.ts +3 -0
  42. package/build/validation/withZod.js +39 -0
  43. package/package.json +7 -2
  44. package/.eslintrc.js +0 -46
  45. package/.github/workflows/test.yml +0 -35
  46. package/.husky/pre-commit +0 -4
  47. package/src/ValidatedForm.tsx +0 -130
  48. package/src/hooks.ts +0 -27
  49. package/src/internal/formContext.ts +0 -18
  50. package/src/internal/util.ts +0 -23
  51. package/src/server.ts +0 -5
  52. package/src/validation/types.ts +0 -12
  53. package/src/validation/validation.test.ts +0 -76
  54. package/src/validation/withYup.ts +0 -37
  55. package/test-app/README.md +0 -53
  56. package/test-app/app/components/Input.tsx +0 -24
  57. package/test-app/app/components/SubmitButton.tsx +0 -18
  58. package/test-app/app/entry.client.tsx +0 -4
  59. package/test-app/app/entry.server.tsx +0 -21
  60. package/test-app/app/root.tsx +0 -246
  61. package/test-app/app/routes/default-values.tsx +0 -34
  62. package/test-app/app/routes/index.tsx +0 -100
  63. package/test-app/app/routes/noscript.tsx +0 -10
  64. package/test-app/app/routes/submission.alt.tsx +0 -6
  65. package/test-app/app/routes/submission.fetcher.tsx +0 -6
  66. package/test-app/app/routes/submission.tsx +0 -47
  67. package/test-app/app/routes/validation.tsx +0 -40
  68. package/test-app/app/styles/dark.css +0 -7
  69. package/test-app/app/styles/demos/about.css +0 -26
  70. package/test-app/app/styles/demos/remix.css +0 -120
  71. package/test-app/app/styles/global.css +0 -98
  72. package/test-app/cypress/fixtures/example.json +0 -5
  73. package/test-app/cypress/integration/default-values.ts +0 -15
  74. package/test-app/cypress/integration/sanity.ts +0 -19
  75. package/test-app/cypress/integration/submission.ts +0 -26
  76. package/test-app/cypress/integration/validation.ts +0 -70
  77. package/test-app/cypress/plugins/config.ts +0 -38
  78. package/test-app/cypress/plugins/index.ts +0 -9
  79. package/test-app/cypress/support/commands/index.ts +0 -13
  80. package/test-app/cypress/support/commands/types.d.ts +0 -11
  81. package/test-app/cypress/support/index.ts +0 -20
  82. package/test-app/cypress/tsconfig.json +0 -11
  83. package/test-app/cypress.json +0 -3
  84. package/test-app/package-lock.json +0 -11675
  85. package/test-app/package.json +0 -40
  86. package/test-app/public/favicon.ico +0 -0
  87. package/test-app/remix.config.js +0 -10
  88. package/test-app/remix.env.d.ts +0 -2
  89. package/test-app/tsconfig.json +0 -18
  90. package/tsconfig.json +0 -15
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"},{"size":207,"mtime":1637876506168,"results":"9","hashOfConfig":"10"},{"size":438,"mtime":1637877226360,"results":"11","hashOfConfig":"10"},{"size":1085,"mtime":1637877476573,"results":"12","hashOfConfig":"10"},{"size":1293,"mtime":1637876566355,"results":"13","hashOfConfig":"10"},{"size":1330,"mtime":1637902697212,"results":"14","hashOfConfig":"10"},{"size":2220,"mtime":1637902736281,"results":"15","hashOfConfig":"10"},{"size":3526,"mtime":1638155421909,"results":"16","hashOfConfig":"10"},{"size":1168,"mtime":1638155747107,"results":"17","hashOfConfig":"10"},{"filePath":"18","messages":"19","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"bt07le",{"filePath":"20","messages":"21","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"22","messages":"23","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"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":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"32","messages":"33","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",["34"],"/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",["35"],"/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",[],{"ruleId":"36","severity":1,"message":"37","line":2,"column":23,"nodeType":"38","messageId":"39","endLine":2,"endColumn":39},{"ruleId":"36","severity":1,"message":"40","line":1,"column":26,"nodeType":"38","messageId":"39","endLine":1,"endColumn":39},"@typescript-eslint/no-unused-vars","'ValidationResult' is defined but never used.","Identifier","unusedVar","'useActionData' is defined but never used."]
package/README.md CHANGED
@@ -1,3 +1,182 @@
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
+ - Validation library agnostic
11
+
12
+ # Demo
13
+
14
+ https://user-images.githubusercontent.com/25882770/143505448-c4b7e660-7a73-4005-b2ca-17c65a15ef46.mov
15
+
16
+ # Getting started
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install remix-validated-form
22
+ ```
23
+
24
+ ## Create an input component
25
+
26
+ In order to display field errors or do field-by-field validation,
27
+ it's recommended to incorporate this library into an input component using `useField`.
28
+
29
+ ```tsx
30
+ import { useField } from "remix-validated-form";
31
+
32
+ type MyInputProps = {
33
+ name: string;
34
+ label: string;
35
+ };
36
+
37
+ export const MyInput = ({ name, label }: InputProps) => {
38
+ const { validate, clearError, defaultValue, error } = useField(name);
39
+ return (
40
+ <div>
41
+ <label htmlFor={name}>{label}</label>
42
+ <input
43
+ id={name}
44
+ name={name}
45
+ onBlur={validate}
46
+ onChange={clearError}
47
+ defaultValue={defaultValue}
48
+ />
49
+ {error && <span className="my-error-class">{error}</span>}
50
+ </div>
51
+ );
52
+ };
53
+ ```
54
+
55
+ ## Create a submit button component
56
+
57
+ To best take advantage of the per-form submission detection, we can create a submit button component.
58
+
59
+ ```tsx
60
+ import { useIsSubmitting } from "../../remix-validated-form";
61
+
62
+ export const MySubmitButton = () => {
63
+ const isSubmitting = useIsSubmitting();
64
+ return (
65
+ <button type="submit" disabled={isSubmitting}>
66
+ {isSubmitting ? "Submitting..." : "Submit"}
67
+ </button>
68
+ );
69
+ };
70
+ ```
71
+
72
+ ## Use the form!
73
+
74
+ Now that we have our components, making a form is easy!
75
+
76
+ ```tsx
77
+ import { ActionFunction, LoaderFunction, redirect, useLoaderData } from "remix";
78
+ import * as yup from "yup";
79
+ import { validationError, ValidatedForm, withYup } from "remix-validated-form";
80
+ import { MyInput, MySubmitButton } from "~/components/Input";
81
+
82
+ // Using yup in this example, but you can use anything
83
+ const validator = withYup(
84
+ yup.object({
85
+ firstName: yup.string().label("First Name").required(),
86
+ lastName: yup.string().label("Last Name").required(),
87
+ email: yup.string().email().label("Email").required(),
88
+ })
89
+ );
90
+
91
+ export const action: ActionFunction = async ({ request }) => {
92
+ const fieldValues = validator.validate(
93
+ Object.fromEntries(await request.formData())
94
+ );
95
+ if (fieldValues.error) return validationError(fieldValues.error);
96
+ const { firstName, lastName, email } = fieldValues.data;
97
+
98
+ // Do something with correctly typed values;
99
+
100
+ return redirect("/");
101
+ };
102
+
103
+ export const loader: LoaderFunction = () => {
104
+ return {
105
+ defaultValues: {
106
+ firstName: "Jane",
107
+ lastName: "Doe",
108
+ email: "jane.doe@example.com",
109
+ },
110
+ };
111
+ };
112
+
113
+ export default function MyForm() {
114
+ const { defaultValues } = useLoaderData();
115
+ return (
116
+ <ValidatedForm
117
+ validator={validator}
118
+ method="post"
119
+ defaultValues={defaultValues}
120
+ >
121
+ <MyInput name="firstName" label="First Name" />
122
+ <MyInput name="lastName" label="Last Name" />
123
+ <MyInput name="email" label="Email" />
124
+ <MySubmitButton />
125
+ </ValidatedForm>
126
+ );
127
+ }
128
+ ```
129
+
130
+ # Validation Library Support
131
+
132
+ This library currently includes an out-of-the-box adapter for `yup` and `zod`,
133
+ but you can easily support whatever library you want by creating your own adapter.
134
+
135
+ And if you create an adapter for a library, feel free to make a PR on this library to add official support 😊
136
+
137
+ ## Creating an adapter
138
+
139
+ Any object that conforms to the `Validator` type can be passed into the the `ValidatedForm`'s `validator` prop.
140
+
141
+ ```ts
142
+ type FieldErrors = Record<string, string>;
143
+
144
+ type ValidationResult<DataType> =
145
+ | { data: DataType; error: undefined }
146
+ | { error: FieldErrors; data: undefined };
147
+
148
+ type ValidateFieldResult = { error?: string };
149
+
150
+ type Validator<DataType> = {
151
+ validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
152
+ validateField: (
153
+ unvalidatedData: unknown,
154
+ field: string
155
+ ) => ValidateFieldResult;
156
+ };
157
+ ```
158
+
159
+ In order to make an adapter for your validation library of choice,
160
+ you can create a function that accepts a schema from the validation library and turns it into a validator.
161
+
162
+ The out-of-the-box support for `yup` in this library works like this:
163
+
164
+ ```ts
165
+ export const withYup = <Schema extends AnyObjectSchema>(
166
+ validationSchema: Schema
167
+ // For best result with Typescript, we should type the `Validator` we return based on the provided schema
168
+ ): Validator<InferType<Schema>> => ({
169
+ validate: (unvalidatedData) => {
170
+ // Validate with yup and return the validated & typed data or the error
171
+
172
+ if (isValid) return { data: { field1: "someValue" }, error: undefined };
173
+ else return { error: { field1: "Some error!" }, data: undefined };
174
+ },
175
+ validateField: (unvalidatedData, field) => {
176
+ // Validate the specific field with yup
177
+
178
+ if (isValid) return { error: undefined };
179
+ else return { error: "Some error" };
180
+ },
181
+ });
182
+ ```
@@ -0,0 +1,11 @@
1
+ import { Form as RemixForm, useFetcher } from "@remix-run/react";
2
+ import React, { ComponentProps } from "react";
3
+ import { Validator } from "./validation/types";
4
+ export declare type FormProps<DataType> = {
5
+ validator: Validator<DataType>;
6
+ onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void;
7
+ fetcher?: ReturnType<typeof useFetcher>;
8
+ defaultValues?: Partial<DataType>;
9
+ formRef?: React.RefObject<HTMLFormElement>;
10
+ } & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
11
+ export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }: FormProps<DataType>): JSX.Element;
@@ -0,0 +1,69 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Form as RemixForm, useActionData, useFormAction, useTransition, } from "@remix-run/react";
3
+ import { useEffect, useMemo, useRef, useState, } from "react";
4
+ import invariant from "tiny-invariant";
5
+ import { FormContext } from "./internal/formContext";
6
+ import { omit, mergeRefs } from "./internal/util";
7
+ function useFieldErrors(fetcher) {
8
+ const actionData = useActionData();
9
+ const dataToUse = fetcher ? fetcher.data : actionData;
10
+ const fieldErrorsFromAction = dataToUse === null || dataToUse === void 0 ? void 0 : dataToUse.fieldErrors;
11
+ const [fieldErrors, setFieldErrors] = useState(fieldErrorsFromAction !== null && fieldErrorsFromAction !== void 0 ? fieldErrorsFromAction : {});
12
+ useEffect(() => {
13
+ if (fieldErrorsFromAction)
14
+ setFieldErrors(fieldErrorsFromAction);
15
+ }, [fieldErrorsFromAction]);
16
+ return [fieldErrors, setFieldErrors];
17
+ }
18
+ const useIsSubmitting = (action, fetcher) => {
19
+ const actionForCurrentPage = useFormAction();
20
+ const pendingFormSubmit = useTransition().submission;
21
+ return fetcher
22
+ ? fetcher.state === "submitting"
23
+ : pendingFormSubmit &&
24
+ pendingFormSubmit.action.endsWith(action !== null && action !== void 0 ? action : actionForCurrentPage);
25
+ };
26
+ const getDataFromForm = (el) => Object.fromEntries(new FormData(el));
27
+ export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
28
+ var _a;
29
+ const [fieldErrors, setFieldErrors] = useFieldErrors(fetcher);
30
+ const isSubmitting = useIsSubmitting(action, fetcher);
31
+ const formRef = useRef(null);
32
+ const contextValue = useMemo(() => ({
33
+ fieldErrors,
34
+ action,
35
+ defaultValues,
36
+ isSubmitting: isSubmitting !== null && isSubmitting !== void 0 ? isSubmitting : false,
37
+ clearError: (fieldName) => {
38
+ setFieldErrors((prev) => omit(prev, fieldName));
39
+ },
40
+ validateField: (fieldName) => {
41
+ invariant(formRef.current, "Cannot find reference to form");
42
+ const { error } = validator.validateField(getDataFromForm(formRef.current), fieldName);
43
+ if (error) {
44
+ setFieldErrors((prev) => ({
45
+ ...prev,
46
+ [fieldName]: error,
47
+ }));
48
+ }
49
+ },
50
+ }), [
51
+ fieldErrors,
52
+ action,
53
+ defaultValues,
54
+ isSubmitting,
55
+ setFieldErrors,
56
+ validator,
57
+ ]);
58
+ const Form = (_a = fetcher === null || fetcher === void 0 ? void 0 : fetcher.Form) !== null && _a !== void 0 ? _a : RemixForm;
59
+ return (_jsx(Form, { ref: mergeRefs([formRef, formRefProp]), ...rest, action: action, onSubmit: (event) => {
60
+ const result = validator.validate(getDataFromForm(event.currentTarget));
61
+ if (result.error) {
62
+ event.preventDefault();
63
+ setFieldErrors(result.error);
64
+ }
65
+ else {
66
+ onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, event);
67
+ }
68
+ }, children: _jsx(FormContext.Provider, { value: contextValue, children: children }, void 0) }, void 0));
69
+ }
@@ -0,0 +1,8 @@
1
+ export declare const useField: (name: string) => {
2
+ error: string;
3
+ clearError: () => void;
4
+ validate: () => void;
5
+ defaultValue: any;
6
+ };
7
+ export declare const useFormContext: () => import("./internal/formContext").FormContextValue;
8
+ export declare const useIsSubmitting: () => boolean;
@@ -0,0 +1,17 @@
1
+ import { useContext, useMemo } from "react";
2
+ import { FormContext } from "./internal/formContext";
3
+ export const useField = (name) => {
4
+ const { fieldErrors, clearError, validateField, defaultValues } = useContext(FormContext);
5
+ const field = useMemo(() => ({
6
+ error: fieldErrors[name],
7
+ clearError: () => {
8
+ clearError(name);
9
+ },
10
+ validate: () => validateField(name),
11
+ defaultValue: defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues[name],
12
+ }), [clearError, defaultValues, fieldErrors, name, validateField]);
13
+ return field;
14
+ };
15
+ // test commit
16
+ export const useFormContext = () => useContext(FormContext);
17
+ export const useIsSubmitting = () => useFormContext().isSubmitting;
File without changes
@@ -0,0 +1,5 @@
1
+ export * from "./hooks";
2
+ export * from "./server";
3
+ export * from "./ValidatedForm";
4
+ export * from "./validation/types";
5
+ export * from "./validation/withYup";
@@ -0,0 +1,13 @@
1
+ /// <reference types="react" />
2
+ import { FieldErrors } from "../validation/types";
3
+ export declare type FormContextValue = {
4
+ fieldErrors: FieldErrors;
5
+ clearError: (...names: string[]) => void;
6
+ validateField: (fieldName: string) => void;
7
+ action?: string;
8
+ isSubmitting: boolean;
9
+ defaultValues?: {
10
+ [fieldName: string]: any;
11
+ };
12
+ };
13
+ export declare const FormContext: import("react").Context<FormContextValue>;
@@ -0,0 +1,7 @@
1
+ import { createContext } from "react";
2
+ export const FormContext = createContext({
3
+ fieldErrors: {},
4
+ clearError: () => { },
5
+ validateField: () => { },
6
+ isSubmitting: false,
7
+ });
@@ -0,0 +1,3 @@
1
+ import type React from "react";
2
+ export declare const omit: (obj: any, ...keys: string[]) => any;
3
+ export declare const mergeRefs: <T = any>(refs: (React.MutableRefObject<T> | React.LegacyRef<T> | undefined)[]) => (instance: T | null) => void;
@@ -0,0 +1,19 @@
1
+ export const omit = (obj, ...keys) => {
2
+ const result = { ...obj };
3
+ for (const key of keys) {
4
+ delete result[key];
5
+ }
6
+ return result;
7
+ };
8
+ export const mergeRefs = (refs) => {
9
+ return (value) => {
10
+ refs.filter(Boolean).forEach((ref) => {
11
+ if (typeof ref === "function") {
12
+ ref(value);
13
+ }
14
+ else if (ref != null) {
15
+ ref.current = value;
16
+ }
17
+ });
18
+ };
19
+ };
@@ -0,0 +1,2 @@
1
+ import { FieldErrors } from "./validation/types";
2
+ export declare const validationError: (errors: FieldErrors) => Response;
@@ -0,0 +1,2 @@
1
+ import { json } from "@remix-run/server-runtime";
2
+ export const validationError = (errors) => json({ fieldErrors: errors }, { status: 422 });
@@ -0,0 +1,15 @@
1
+ export declare type FieldErrors = Record<string, string>;
2
+ export declare type ValidationResult<DataType> = {
3
+ data: DataType;
4
+ error: undefined;
5
+ } | {
6
+ error: FieldErrors;
7
+ data: undefined;
8
+ };
9
+ export declare type ValidateFieldResult = {
10
+ error?: string;
11
+ };
12
+ export declare type Validator<DataType> = {
13
+ validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
14
+ validateField: (unvalidatedData: unknown, field: string) => ValidateFieldResult;
15
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,120 @@
1
+ import * as yup from "yup";
2
+ import { z } from "zod";
3
+ import { withYup } from "..";
4
+ import { withZod } from "./withZod";
5
+ const validationTestCases = [
6
+ {
7
+ name: "yup",
8
+ validator: withYup(yup.object({
9
+ firstName: yup.string().required(),
10
+ lastName: yup.string().required(),
11
+ age: yup.number(),
12
+ })),
13
+ },
14
+ {
15
+ name: "zod",
16
+ validator: withZod(z.object({
17
+ firstName: z.string().nonempty(),
18
+ lastName: z.string().nonempty(),
19
+ age: z.optional(z.number()),
20
+ })),
21
+ },
22
+ ];
23
+ // Not going to enforce exact error strings here
24
+ const anyString = expect.any(String);
25
+ describe("Validation", () => {
26
+ describe.each(validationTestCases)("Adapter for $name", ({ validator }) => {
27
+ describe("validate", () => {
28
+ it("should return the data when valid", () => {
29
+ const obj = {
30
+ firstName: "John",
31
+ lastName: "Doe",
32
+ age: 30,
33
+ };
34
+ expect(validator.validate(obj)).toEqual({
35
+ data: obj,
36
+ error: undefined,
37
+ });
38
+ });
39
+ it("should return field errors when invalid", () => {
40
+ const obj = { age: "hi!" };
41
+ expect(validator.validate(obj)).toEqual({
42
+ data: undefined,
43
+ error: {
44
+ firstName: anyString,
45
+ lastName: anyString,
46
+ age: anyString,
47
+ },
48
+ });
49
+ });
50
+ });
51
+ describe("validateField", () => {
52
+ it("should not return an error if field is valid", () => {
53
+ const obj = {
54
+ firstName: "John",
55
+ lastName: {}, // invalid, but we should only be validating firstName
56
+ };
57
+ expect(validator.validateField(obj, "firstName")).toEqual({
58
+ error: undefined,
59
+ });
60
+ });
61
+ it("should return an error if field is invalid", () => {
62
+ const obj = { firstName: "John", lastName: {} };
63
+ expect(validator.validateField(obj, "lastName")).toEqual({
64
+ error: anyString,
65
+ });
66
+ });
67
+ });
68
+ });
69
+ });
70
+ describe("withZod", () => {
71
+ it("returns coherent errors for complex schemas", () => {
72
+ const schema = z.union([
73
+ z.object({
74
+ type: z.literal("foo"),
75
+ foo: z.string(),
76
+ }),
77
+ z.object({
78
+ type: z.literal("bar"),
79
+ bar: z.string(),
80
+ }),
81
+ ]);
82
+ const obj = {
83
+ type: "foo",
84
+ bar: 123,
85
+ foo: 123,
86
+ };
87
+ expect(withZod(schema).validate(obj)).toEqual({
88
+ data: undefined,
89
+ error: {
90
+ type: anyString,
91
+ bar: anyString,
92
+ foo: anyString,
93
+ },
94
+ });
95
+ });
96
+ it("returns errors for fields that are unions", () => {
97
+ const schema = z.object({
98
+ field1: z.union([z.literal("foo"), z.literal("bar")]),
99
+ field2: z.union([z.literal("foo"), z.literal("bar")]),
100
+ });
101
+ const obj = {
102
+ field1: "a value",
103
+ // field2 missing
104
+ };
105
+ const validator = withZod(schema);
106
+ expect(validator.validate(obj)).toEqual({
107
+ data: undefined,
108
+ error: {
109
+ field1: anyString,
110
+ field2: anyString,
111
+ },
112
+ });
113
+ expect(validator.validateField(obj, "field1")).toEqual({
114
+ error: anyString,
115
+ });
116
+ expect(validator.validateField(obj, "field2")).toEqual({
117
+ error: anyString,
118
+ });
119
+ });
120
+ });
@@ -0,0 +1,3 @@
1
+ import type { AnyObjectSchema, InferType } from "yup";
2
+ import { Validator } from "./types";
3
+ export declare const withYup: <Schema extends AnyObjectSchema>(validationSchema: Schema) => Validator<InferType<Schema>>;
@@ -0,0 +1,34 @@
1
+ const validationErrorToFieldErrors = (error) => {
2
+ const fieldErrors = {};
3
+ error.inner.forEach((innerError) => {
4
+ if (!innerError.path)
5
+ return;
6
+ fieldErrors[innerError.path] = innerError.message;
7
+ });
8
+ return fieldErrors;
9
+ };
10
+ export const withYup = (validationSchema) => ({
11
+ validate: (data) => {
12
+ try {
13
+ const validated = validationSchema.validateSync(data, {
14
+ abortEarly: false,
15
+ });
16
+ return { data: validated, error: undefined };
17
+ }
18
+ catch (err) {
19
+ return {
20
+ error: validationErrorToFieldErrors(err),
21
+ data: undefined,
22
+ };
23
+ }
24
+ },
25
+ validateField: (data, field) => {
26
+ try {
27
+ validationSchema.validateSyncAt(field, data);
28
+ return {};
29
+ }
30
+ catch (err) {
31
+ return { error: err.message };
32
+ }
33
+ },
34
+ });
@@ -0,0 +1,3 @@
1
+ import type { z } from "zod";
2
+ import { Validator } from "..";
3
+ export declare function withZod<T>(zodSchema: z.Schema<T>): Validator<T>;
@@ -0,0 +1,35 @@
1
+ const getIssuesForError = (err) => {
2
+ return err.issues.flatMap((issue) => {
3
+ if ("unionErrors" in issue) {
4
+ return issue.unionErrors.flatMap((err) => getIssuesForError(err));
5
+ }
6
+ else {
7
+ return [issue];
8
+ }
9
+ });
10
+ };
11
+ export function withZod(zodSchema) {
12
+ return {
13
+ validate: (value) => {
14
+ const result = zodSchema.safeParse(value);
15
+ if (result.success)
16
+ return { data: result.data, error: undefined };
17
+ const fieldErrors = {};
18
+ getIssuesForError(result.error).forEach((issue) => {
19
+ const path = issue.path.join(".");
20
+ if (!fieldErrors[path])
21
+ fieldErrors[path] = issue.message;
22
+ });
23
+ return { error: fieldErrors, data: undefined };
24
+ },
25
+ validateField: (data, field) => {
26
+ var _a;
27
+ const result = zodSchema.safeParse(data);
28
+ if (result.success)
29
+ return { error: undefined };
30
+ return {
31
+ error: (_a = getIssuesForError(result.error).find((issue) => issue.path.join(".") === field)) === null || _a === void 0 ? void 0 : _a.message,
32
+ };
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,11 @@
1
+ import { Form as RemixForm, useFetcher } from "@remix-run/react";
2
+ import React, { ComponentProps } from "react";
3
+ import { Validator } from "./validation/types";
4
+ export declare type FormProps<DataType> = {
5
+ validator: Validator<DataType>;
6
+ onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void;
7
+ fetcher?: ReturnType<typeof useFetcher>;
8
+ defaultValues?: Partial<DataType>;
9
+ formRef?: React.RefObject<HTMLFormElement>;
10
+ } & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
11
+ export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }: FormProps<DataType>): JSX.Element;