remix-validated-form 0.0.3 → 0.0.4

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 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"},{"size":207,"mtime":1637876506168,"results":"5","hashOfConfig":"6"},{"size":438,"mtime":1637877226360,"results":"7","hashOfConfig":"6"},{"size":1085,"mtime":1637877476573,"results":"8","hashOfConfig":"6"},{"size":1293,"mtime":1637876566355,"results":"9","hashOfConfig":"6"},{"filePath":"10","messages":"11","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"bt07le",{"filePath":"12","messages":"13","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"14","messages":"15","errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"16","messages":"17","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",["18"],"/Users/aaronpettengill/dev/remix-validated-form/test-app/app/routes/validation.tsx",[],{"ruleId":"19","severity":1,"message":"20","line":2,"column":23,"nodeType":"21","messageId":"22","endLine":2,"endColumn":39},"@typescript-eslint/no-unused-vars","'ValidationResult' is defined but never used.","Identifier","unusedVar"]
package/README.md CHANGED
@@ -1,3 +1,178 @@
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
+ # Getting started
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install remix-validated-form
18
+ ```
19
+
20
+ ## Create an input component
21
+
22
+ In order to display field errors or do field-by-field validation,
23
+ it's recommended to incorporate this library into an input component using `useField`.
24
+
25
+ ```tsx
26
+ import { useField } from "remix-validated-form";
27
+
28
+ type MyInputProps = {
29
+ name: string;
30
+ label: string;
31
+ };
32
+
33
+ export const MyInput = ({ name, label }: InputProps) => {
34
+ const { validate, clearError, defaultValue, error } = useField(name);
35
+ return (
36
+ <div>
37
+ <label htmlFor={name}>{label}</label>
38
+ <input
39
+ id={name}
40
+ name={name}
41
+ onBlur={validate}
42
+ onChange={clearError}
43
+ defaultValue={defaultValue}
44
+ />
45
+ {error && <span className="my-error-class">{error}</span>}
46
+ </div>
47
+ );
48
+ };
49
+ ```
50
+
51
+ ## Create a submit button component
52
+
53
+ To best take advantage of the per-form submission detection, we can create a submit button component.
54
+
55
+ ```tsx
56
+ import { useIsSubmitting } from "../../remix-validated-form";
57
+
58
+ export const MySubmitButton = () => {
59
+ const isSubmitting = useIsSubmitting();
60
+ return (
61
+ <button type="submit" disabled={isSubmitting}>
62
+ {isSubmitting ? "Submitting..." : "Submit"}
63
+ </button>
64
+ );
65
+ };
66
+ ```
67
+
68
+ ## Use the form!
69
+
70
+ Now that we have our components, making a form is easy!
71
+
72
+ ```tsx
73
+ import { ActionFunction, LoaderFunction, redirect, useLoaderData } from "remix";
74
+ import * as yup from "yup";
75
+ import { validationError, ValidatedForm, withYup } from "remix-validated-form";
76
+ import { MyInput, MySubmitButton } from "~/components/Input";
77
+
78
+ // Using yup in this example, but you can use anything
79
+ const validator = withYup(
80
+ yup.object({
81
+ firstName: yup.string().label("First Name").required(),
82
+ lastName: yup.string().label("Last Name").required(),
83
+ email: yup.string().email().label("Email").required(),
84
+ })
85
+ );
86
+
87
+ export const action: ActionFunction = async ({ request }) => {
88
+ const fieldValues = validator.validate(
89
+ Object.fromEntries(await request.formData())
90
+ );
91
+ if (fieldValues.error) return validationError(fieldValues.error);
92
+ const { firstName, lastName, email } = fieldValues.data;
93
+
94
+ // Do something with correctly typed values;
95
+
96
+ return redirect("/");
97
+ };
98
+
99
+ export const loader: LoaderFunction = () => {
100
+ return {
101
+ defaultValues: {
102
+ firstName: "Jane",
103
+ lastName: "Doe",
104
+ email: "jane.doe@example.com",
105
+ },
106
+ };
107
+ };
108
+
109
+ export default function MyForm() {
110
+ const { defaultValues } = useLoaderData();
111
+ return (
112
+ <ValidatedForm
113
+ validator={validator}
114
+ method="post"
115
+ defaultValues={defaultValues}
116
+ >
117
+ <MyInput name="firstName" label="First Name" />
118
+ <MyInput name="lastName" label="Last Name" />
119
+ <MyInput name="email" label="Email" />
120
+ <MySubmitButton />
121
+ </ValidatedForm>
122
+ );
123
+ }
124
+ ```
125
+
126
+ # Validation Library Support
127
+
128
+ This lbirary currently includes an out-of-the-box adapter for `yup`,
129
+ but you can easily support whatever library you want by creating your own adapter.
130
+
131
+ And if you create an adapter for a library, feel free to make a PR on this library to add official support 😊
132
+
133
+ ## Creating an adapter
134
+
135
+ Any object that conforms to the `Validator` type can be passed into the the `ValidatedForm`'s `validator` prop.
136
+
137
+ ```ts
138
+ type FieldErrors = Record<string, string>;
139
+
140
+ type ValidationResult<DataType> =
141
+ | { data: DataType; error: undefined }
142
+ | { error: FieldErrors; data: undefined };
143
+
144
+ type ValidateFieldResult = { error?: string };
145
+
146
+ type Validator<DataType> = {
147
+ validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
148
+ validateField: (
149
+ unvalidatedData: unknown,
150
+ field: string
151
+ ) => ValidateFieldResult;
152
+ };
153
+ ```
154
+
155
+ In order to make an adapter for your validation library of choice,
156
+ you can create a function that accepts a schema from the validation library and turns it into a validator.
157
+
158
+ The out-of-the-box support for `yup` in this library works like this:
159
+
160
+ ```ts
161
+ export const withYup = <Schema extends AnyObjectSchema>(
162
+ validationSchema: Schema
163
+ // For best result with Typescript, we should type the `Validator` we return based on the provided schema
164
+ ): Validator<InferType<Schema>> => ({
165
+ validate: (unvalidatedData) => {
166
+ // Validate with yup and return the validated & typed data or the error
167
+
168
+ if (isValid) return { data: { field1: "someValue" }, error: undefined };
169
+ else return { error: { field1: "Some error!" }, data: undefined };
170
+ },
171
+ validateField: (unvalidatedData, field) => {
172
+ // Validate the specific field with yup
173
+
174
+ if (isValid) return { error: undefined };
175
+ else return { error: "Some error" };
176
+ },
177
+ });
178
+ ```
@@ -1,2 +1,2 @@
1
1
  import { FieldErrors } from "./validation/types";
2
- export declare const fieldErrors: (errors: FieldErrors) => Response;
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 fieldErrors = (errors) => json({ fieldErrors: errors }, { status: 422 });
2
+ export const validationError = (errors) => json({ fieldErrors: errors }, { status: 422 });
@@ -10,6 +10,6 @@ export declare type ValidateFieldResult = {
10
10
  error?: string;
11
11
  };
12
12
  export declare type Validator<DataType> = {
13
- validate: (formData: unknown) => ValidationResult<DataType>;
14
- validateField: (formData: unknown, field: string) => ValidateFieldResult;
13
+ validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
14
+ validateField: (unvalidatedData: unknown, field: string) => ValidateFieldResult;
15
15
  };
package/build/server.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import { FieldErrors } from "./validation/types";
2
- export declare const fieldErrors: (errors: FieldErrors) => Response;
2
+ export declare const validationError: (errors: FieldErrors) => Response;
package/build/server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fieldErrors = void 0;
3
+ exports.validationError = void 0;
4
4
  const server_runtime_1 = require("@remix-run/server-runtime");
5
- const fieldErrors = (errors) => (0, server_runtime_1.json)({ fieldErrors: errors }, { status: 422 });
6
- exports.fieldErrors = fieldErrors;
5
+ const validationError = (errors) => (0, server_runtime_1.json)({ fieldErrors: errors }, { status: 422 });
6
+ exports.validationError = validationError;
@@ -10,6 +10,6 @@ export declare type ValidateFieldResult = {
10
10
  error?: string;
11
11
  };
12
12
  export declare type Validator<DataType> = {
13
- validate: (formData: unknown) => ValidationResult<DataType>;
14
- validateField: (formData: unknown, field: string) => ValidateFieldResult;
13
+ validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
14
+ validateField: (unvalidatedData: unknown, field: string) => ValidateFieldResult;
15
15
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remix-validated-form",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
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",