remix-validated-form 2.0.1-beta.0 → 2.0.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ $ jest src
2
+  PASS  src/validation/validation.test.ts
3
+ Validation
4
+ Adapter for yup
5
+ validate
6
+ ✓ should return the data when valid (2 ms)
7
+ ✓ should return field errors when invalid (2 ms)
8
+ ✓ should unflatten data when validating
9
+ ✓ should accept FormData directly and return errors
10
+ ✓ should accept FormData directly and return valid data (1 ms)
11
+ validateField
12
+ ✓ should not return an error if field is valid
13
+ ✓ should not return an error if a nested field is valid (1 ms)
14
+ ✓ should return an error if field is invalid
15
+ ✓ should return an error if a nested field is invalid
16
+ Adapter for zod
17
+ validate
18
+ ✓ should return the data when valid (2 ms)
19
+ ✓ should return field errors when invalid
20
+ ✓ should unflatten data when validating (1 ms)
21
+ ✓ should accept FormData directly and return errors
22
+ ✓ should accept FormData directly and return valid data
23
+ validateField
24
+ ✓ should not return an error if field is valid
25
+ ✓ should not return an error if a nested field is valid (1 ms)
26
+ ✓ should return an error if field is invalid
27
+ ✓ should return an error if a nested field is invalid
28
+ withZod
29
+ ✓ returns coherent errors for complex schemas (1 ms)
30
+ ✓ returns errors for fields that are unions
31
+
32
+ Test Suites: 1 passed, 1 total
33
+ Tests: 20 passed, 20 total
34
+ Snapshots: 0 total
35
+ Time: 1.526 s, estimated 2 s
36
+ Ran all test suites matching /src/i.
package/README.md ADDED
@@ -0,0 +1,235 @@
1
+ # Remix Validated Form
2
+
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
+ ```
20
+ git clone https://github.com/airjp73/remix-validated-form
21
+ cd remix-validated-form
22
+ npm i
23
+ cd sample-app
24
+ npm i
25
+ cd ..
26
+ npm run sample-app
27
+ ```
28
+
29
+ # Getting started
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ npm install remix-validated-form
35
+ ```
36
+
37
+ ## Create an input component
38
+
39
+ In order to display field errors or do field-by-field validation,
40
+ it's recommended to incorporate this library into an input component using `useField`.
41
+
42
+ ```tsx
43
+ import { useField } from "remix-validated-form";
44
+
45
+ type MyInputProps = {
46
+ name: string;
47
+ label: string;
48
+ };
49
+
50
+ export const MyInput = ({ name, label }: InputProps) => {
51
+ const { validate, clearError, defaultValue, error } = useField(name);
52
+ return (
53
+ <div>
54
+ <label htmlFor={name}>{label}</label>
55
+ <input
56
+ id={name}
57
+ name={name}
58
+ onBlur={validate}
59
+ onChange={clearError}
60
+ defaultValue={defaultValue}
61
+ />
62
+ {error && <span className="my-error-class">{error}</span>}
63
+ </div>
64
+ );
65
+ };
66
+ ```
67
+
68
+ ## Create a submit button component
69
+
70
+ To best take advantage of the per-form submission detection, we can create a submit button component.
71
+
72
+ ```tsx
73
+ import { useIsSubmitting } from "remix-validated-form";
74
+
75
+ export const MySubmitButton = () => {
76
+ const isSubmitting = useIsSubmitting();
77
+ return (
78
+ <button type="submit" disabled={isSubmitting}>
79
+ {isSubmitting ? "Submitting..." : "Submit"}
80
+ </button>
81
+ );
82
+ };
83
+ ```
84
+
85
+ ## Use the form!
86
+
87
+ Now that we have our components, making a form is easy!
88
+
89
+ ```tsx
90
+ import { ActionFunction, LoaderFunction, redirect, useLoaderData } from "remix";
91
+ import * as yup from "yup";
92
+ import { validationError, ValidatedForm, withYup } from "remix-validated-form";
93
+ import { MyInput, MySubmitButton } from "~/components/Input";
94
+
95
+ // Using yup in this example, but you can use anything
96
+ const validator = withYup(
97
+ yup.object({
98
+ firstName: yup.string().label("First Name").required(),
99
+ lastName: yup.string().label("Last Name").required(),
100
+ email: yup.string().email().label("Email").required(),
101
+ })
102
+ );
103
+
104
+ export const action: ActionFunction = async ({ request }) => {
105
+ const fieldValues = validator.validate(await request.formData());
106
+ if (fieldValues.error) return validationError(fieldValues.error);
107
+ const { firstName, lastName, email } = fieldValues.data;
108
+
109
+ // Do something with correctly typed values;
110
+
111
+ return redirect("/");
112
+ };
113
+
114
+ export const loader: LoaderFunction = () => {
115
+ return {
116
+ defaultValues: {
117
+ firstName: "Jane",
118
+ lastName: "Doe",
119
+ email: "jane.doe@example.com",
120
+ },
121
+ };
122
+ };
123
+
124
+ export default function MyForm() {
125
+ const { defaultValues } = useLoaderData();
126
+ return (
127
+ <ValidatedForm
128
+ validator={validator}
129
+ method="post"
130
+ defaultValues={defaultValues}
131
+ >
132
+ <MyInput name="firstName" label="First Name" />
133
+ <MyInput name="lastName" label="Last Name" />
134
+ <MyInput name="email" label="Email" />
135
+ <MySubmitButton />
136
+ </ValidatedForm>
137
+ );
138
+ }
139
+ ```
140
+
141
+ ## Nested objects and arrays
142
+
143
+ You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
144
+
145
+ ```tsx
146
+ export default function MyForm() {
147
+ const { defaultValues } = useLoaderData();
148
+ return (
149
+ <ValidatedForm
150
+ validator={validator}
151
+ method="post"
152
+ defaultValues={defaultValues}
153
+ >
154
+ <MyInput name="firstName" label="First Name" />
155
+ <MyInput name="lastName" label="Last Name" />
156
+ <MyInput name="address.street" label="Street" />
157
+ <MyInput name="address.city" label="City" />
158
+ <MyInput name="phones[0].type" label="Phone 1 Type" />
159
+ <MyInput name="phones[0].number" label="Phone 1 Number" />
160
+ <MyInput name="phones[1].type" label="Phone 2 Type" />
161
+ <MyInput name="phones[1].number" label="Phone 2 Number" />
162
+ <MySubmitButton />
163
+ </ValidatedForm>
164
+ );
165
+ }
166
+ ```
167
+
168
+ # Validation Library Support
169
+
170
+ This library currently includes an out-of-the-box adapter for `yup` and `zod`,
171
+ but you can easily support whatever library you want by creating your own adapter.
172
+
173
+ And if you create an adapter for a library, feel free to make a PR on this library to add official support 😊
174
+
175
+ ## Creating an adapter
176
+
177
+ Any object that conforms to the `Validator` type can be passed into the the `ValidatedForm`'s `validator` prop.
178
+
179
+ ```ts
180
+ type FieldErrors = Record<string, string>;
181
+
182
+ type ValidationResult<DataType> =
183
+ | { data: DataType; error: undefined }
184
+ | { error: FieldErrors; data: undefined };
185
+
186
+ type ValidateFieldResult = { error?: string };
187
+
188
+ type Validator<DataType> = {
189
+ validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
190
+ validateField: (
191
+ unvalidatedData: unknown,
192
+ field: string
193
+ ) => ValidateFieldResult;
194
+ };
195
+ ```
196
+
197
+ In order to make an adapter for your validation library of choice,
198
+ you can create a function that accepts a schema from the validation library and turns it into a validator.
199
+
200
+ Note the use of `createValidator`.
201
+ It takes care of unflattening the data for nested objects and arrays
202
+ since the form doesn't know anything about object and arrays and this should be handled by the adapter.
203
+ For more on this you can check the implementations for `withZod` and `withYup`.
204
+
205
+ The out-of-the-box support for `yup` in this library works like this:
206
+
207
+ ```ts
208
+ export const withYup = <Schema extends AnyObjectSchema>(
209
+ validationSchema: Schema
210
+ // For best result with Typescript, we should type the `Validator` we return based on the provided schema
211
+ ): Validator<InferType<Schema>> =>
212
+ createValidator({
213
+ validate: (unvalidatedData) => {
214
+ // Validate with yup and return the validated & typed data or the error
215
+
216
+ if (isValid) return { data: { field1: "someValue" }, error: undefined };
217
+ else return { error: { field1: "Some error!" }, data: undefined };
218
+ },
219
+ validateField: (unvalidatedData, field) => {
220
+ // Validate the specific field with yup
221
+
222
+ if (isValid) return { error: undefined };
223
+ else return { error: "Some error" };
224
+ },
225
+ });
226
+ ```
227
+
228
+ # Frequenty Asked Questions
229
+
230
+ ## Why are my fields triggering the native HTML validations before `remix-validated-form` ones?
231
+
232
+ This is happening because you or the library you are using is passing the `required` attribute to the fields.
233
+ This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors.
234
+ If you wan't to disable all native HTML validations you can add `noValidate` to `<ValidatedForm>`.
235
+ We recommend this approach since the validation will still work even if JS is disabled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remix-validated-form",
3
- "version": "2.0.1-beta.0",
3
+ "version": "2.0.1-beta.1",
4
4
  "description": "Form component and utils for easy form validation in remix",
5
5
  "browser": "./browser/index.js",
6
6
  "main": "./build/index.js",
@@ -16,7 +16,8 @@
16
16
  "build:main": "tsc --module CommonJS --outDir ./build",
17
17
  "test": "jest src",
18
18
  "test:watch": "jest src --watch",
19
- "prepublishOnly": "npm run build:browser && npm run build:main"
19
+ "prepublishOnly": "cp ../../README.md ./README.md && npm run build",
20
+ "postpublishOnly": "rm ./README.md"
20
21
  },
21
22
  "author": {
22
23
  "name": "Aaron Pettengill",
@@ -54,6 +55,5 @@
54
55
  "dependencies": {
55
56
  "lodash": "^4.17.21",
56
57
  "tiny-invariant": "^1.2.0"
57
- },
58
- "gitHead": "dab8f221d7c0c5131504215f5c19e3ecdfef97fb"
58
+ }
59
59
  }
@@ -1,9 +0,0 @@
1
- $ npm run build:browser && npm run build:main
2
-
3
- > remix-validated-form@2.0.0 build:browser
4
- > tsc --module ESNext --outDir ./browser
5
-
6
-
7
- > remix-validated-form@2.0.0 build:main
8
- > tsc --module CommonJS --outDir ./build
9
-
File without changes