Skip to content

Commit b75a95a

Browse files
authored
feat(standard-schema): add standard-schema resolver (#738)
1 parent 12d7d8e commit b75a95a

14 files changed

+452
-3
lines changed

README.md

+67
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ Install your preferred validation library alongside `@hookform/resolvers`.
5353
- [effect-ts](#effect-ts)
5454
- [VineJS](#vinejs)
5555
- [fluentvalidation-ts](#fluentvalidation-ts)
56+
- [standard-schema](#standard-schema)
5657
- [Backers](#backers)
5758
- [Sponsors](#sponsors)
5859
- [Contributors](#contributors)
@@ -779,6 +780,72 @@ const App = () => {
779780
};
780781
```
781782

783+
### [standard-schema](https://github.com/standard-schema/standard-schema)
784+
785+
A standard interface for TypeScript schema validation libraries
786+
787+
[![npm](https://img.shields.io/bundlephobia/minzip/@standard-schema/spec?style=for-the-badge)](https://bundlephobia.com/result?p=@standard-schema/spec)
788+
789+
Example zod
790+
791+
```typescript jsx
792+
import { useForm } from 'react-hook-form';
793+
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
794+
import { z } from 'zod';
795+
796+
const schema = z.object({
797+
name: z.string().min(1, { message: 'Required' }),
798+
age: z.number().min(10),
799+
});
800+
801+
const App = () => {
802+
const {
803+
register,
804+
handleSubmit,
805+
formState: { errors },
806+
} = useForm({
807+
resolver: standardSchemaResolver(schema),
808+
});
809+
810+
return (
811+
<form onSubmit={handleSubmit((d) => console.log(d))}>
812+
<input {...register('name')} />
813+
{errors.name?.message && <p>{errors.name?.message}</p>}
814+
<input type="number" {...register('age', { valueAsNumber: true })} />
815+
{errors.age?.message && <p>{errors.age?.message}</p>}
816+
<input type="submit" />
817+
</form>
818+
);
819+
};
820+
```
821+
822+
Example arkType
823+
824+
```typescript jsx
825+
import { useForm } from 'react-hook-form';
826+
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
827+
import { type } from 'arktype';
828+
829+
const schema = type({
830+
username: 'string>1',
831+
password: 'string>1',
832+
});
833+
834+
const App = () => {
835+
const { register, handleSubmit } = useForm({
836+
resolver: standardSchemaResolver(schema),
837+
});
838+
839+
return (
840+
<form onSubmit={handleSubmit((d) => console.log(d))}>
841+
<input {...register('username')} />
842+
<input type="password" {...register('password')} />
843+
<input type="submit" />
844+
</form>
845+
);
846+
};
847+
```
848+
782849
## Backers
783850

784851
Thanks go to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].

bun.lockb

374 Bytes
Binary file not shown.

config/node-13-exports.js

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const subRepositories = [
2020
'effect-ts',
2121
'vine',
2222
'fluentvalidation-ts',
23+
'standard-schema',
2324
];
2425

2526
const copySrc = () => {

effect-ts/src/effect-ts.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
22
import { Effect } from 'effect';
33

44
import { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';
5-
import { appendErrors, type FieldError } from 'react-hook-form';
5+
import { type FieldError, appendErrors } from 'react-hook-form';
66
import type { Resolver } from './types';
77

88
export const effectTsResolver: Resolver =

package.json

+14-2
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,12 @@
123123
"import": "./fluentvalidation-ts/dist/fluentvalidation-ts.mjs",
124124
"require": "./fluentvalidation-ts/dist/fluentvalidation-ts.js"
125125
},
126+
"./standard-schema": {
127+
"types": "./standard-schema/dist/index.d.ts",
128+
"umd": "./standard-schema/dist/standard-schema.umd.js",
129+
"import": "./standard-schema/dist/standard-schema.mjs",
130+
"require": "./standard-schema/dist/standard-schema.js"
131+
},
126132
"./package.json": "./package.json",
127133
"./*": "./*"
128134
},
@@ -184,7 +190,10 @@
184190
"vine/dist",
185191
"fluentvalidation-ts/package.json",
186192
"fluentvalidation-ts/src",
187-
"fluentvalidation-ts/dist"
193+
"fluentvalidation-ts/dist",
194+
"standard-schema/package.json",
195+
"standard-schema/src",
196+
"standard-schema/dist"
188197
],
189198
"publishConfig": {
190199
"access": "public"
@@ -211,6 +220,7 @@
211220
"build:effect-ts": "microbundle --cwd effect-ts --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,effect=Effect,effect/SchemaAST=EffectSchemaAST,effect/ParseResult=EffectParseResult",
212221
"build:vine": "microbundle --cwd vine --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@vinejs/vine=vine",
213222
"build:fluentvalidation-ts": "microbundle --cwd fluentvalidation-ts --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm",
223+
"build:standard-schema": "microbundle --cwd standard-schema --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@standard-schema/spec=standardSchema",
214224
"postbuild": "node ./config/node-13-exports.js && check-export-map",
215225
"lint": "bunx @biomejs/biome check --write --vcs-use-ignore-file=true .",
216226
"lint:types": "tsc",
@@ -243,7 +253,8 @@
243253
"arktype",
244254
"typeschema",
245255
"vine",
246-
"fluentvalidation-ts"
256+
"fluentvalidation-ts",
257+
"standard-schema"
247258
],
248259
"repository": {
249260
"type": "git",
@@ -257,6 +268,7 @@
257268
"homepage": "https://react-hook-form.com",
258269
"devDependencies": {
259270
"@sinclair/typebox": "^0.34.15",
271+
"@standard-schema/spec": "^1.0.0",
260272
"@testing-library/dom": "^10.4.0",
261273
"@testing-library/jest-dom": "^6.6.3",
262274
"@testing-library/react": "^16.2.0",

standard-schema/package.json

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"name": "@hookform/resolvers/standard-schema",
3+
"amdName": "hookformResolversStandardSchema",
4+
"version": "1.0.0",
5+
"private": true,
6+
"description": "React Hook Form validation resolver: standard-schema",
7+
"main": "dist/standard-schema.js",
8+
"module": "dist/standard-schema.module.js",
9+
"umd:main": "dist/standard-schema.umd.js",
10+
"source": "src/index.ts",
11+
"types": "dist/index.d.ts",
12+
"license": "MIT",
13+
"peerDependencies": {
14+
"react-hook-form": "^7.0.0",
15+
"@standard-schema/spec": "^1.0.0",
16+
"@hookform/resolvers": "^2.0.0"
17+
}
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { render, screen } from '@testing-library/react';
2+
import user from '@testing-library/user-event';
3+
import { type } from 'arktype';
4+
import React from 'react';
5+
import { useForm } from 'react-hook-form';
6+
import { standardSchemaResolver } from '..';
7+
8+
const schema = type({
9+
username: 'string>1',
10+
password: 'string>1',
11+
});
12+
13+
type FormData = typeof schema.infer;
14+
15+
interface Props {
16+
onSubmit: (data: FormData) => void;
17+
}
18+
19+
function TestComponent({ onSubmit }: Props) {
20+
const { register, handleSubmit } = useForm<FormData>({
21+
resolver: standardSchemaResolver(schema),
22+
shouldUseNativeValidation: true,
23+
});
24+
25+
return (
26+
<form onSubmit={handleSubmit(onSubmit)}>
27+
<input {...register('username')} placeholder="username" />
28+
29+
<input {...register('password')} placeholder="password" />
30+
31+
<button type="submit">submit</button>
32+
</form>
33+
);
34+
}
35+
36+
test("form's native validation with arkType", async () => {
37+
const handleSubmit = vi.fn();
38+
render(<TestComponent onSubmit={handleSubmit} />);
39+
40+
// username
41+
let usernameField = screen.getByPlaceholderText(
42+
/username/i,
43+
) as HTMLInputElement;
44+
expect(usernameField.validity.valid).toBe(true);
45+
expect(usernameField.validationMessage).toBe('');
46+
47+
// password
48+
let passwordField = screen.getByPlaceholderText(
49+
/password/i,
50+
) as HTMLInputElement;
51+
expect(passwordField.validity.valid).toBe(true);
52+
expect(passwordField.validationMessage).toBe('');
53+
54+
await user.click(screen.getByText(/submit/i));
55+
56+
// username
57+
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
58+
expect(usernameField.validity.valid).toBe(false);
59+
expect(usernameField.validationMessage).toBe(
60+
'username must be at least length 2',
61+
);
62+
63+
// password
64+
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
65+
expect(passwordField.validity.valid).toBe(false);
66+
expect(passwordField.validationMessage).toBe(
67+
'password must be at least length 2',
68+
);
69+
70+
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
71+
await user.type(screen.getByPlaceholderText(/password/i), 'password');
72+
73+
// username
74+
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
75+
expect(usernameField.validity.valid).toBe(true);
76+
expect(usernameField.validationMessage).toBe('');
77+
78+
// password
79+
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
80+
expect(passwordField.validity.valid).toBe(true);
81+
expect(passwordField.validationMessage).toBe('');
82+
});
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { render, screen } from '@testing-library/react';
2+
import user from '@testing-library/user-event';
3+
import { type } from 'arktype';
4+
import React from 'react';
5+
import { useForm } from 'react-hook-form';
6+
import { standardSchemaResolver } from '..';
7+
8+
const schema = type({
9+
username: 'string>1',
10+
password: 'string>1',
11+
});
12+
13+
type FormData = typeof schema.infer & { unusedProperty: string };
14+
15+
interface Props {
16+
onSubmit: (data: FormData) => void;
17+
}
18+
19+
function TestComponent({ onSubmit }: Props) {
20+
const {
21+
register,
22+
handleSubmit,
23+
formState: { errors },
24+
} = useForm<FormData>({
25+
resolver: standardSchemaResolver(schema), // Useful to check TypeScript regressions
26+
});
27+
28+
return (
29+
<form onSubmit={handleSubmit(onSubmit)}>
30+
<input {...register('username')} />
31+
{errors.username && <span role="alert">{errors.username.message}</span>}
32+
33+
<input {...register('password')} />
34+
{errors.password && <span role="alert">{errors.password.message}</span>}
35+
36+
<button type="submit">submit</button>
37+
</form>
38+
);
39+
}
40+
41+
test("form's validation with arkType and TypeScript's integration", async () => {
42+
const handleSubmit = vi.fn();
43+
render(<TestComponent onSubmit={handleSubmit} />);
44+
45+
expect(screen.queryAllByRole('alert')).toHaveLength(0);
46+
47+
await user.click(screen.getByText(/submit/i));
48+
49+
expect(
50+
screen.getByText('username must be at least length 2'),
51+
).toBeInTheDocument();
52+
expect(
53+
screen.getByText('password must be at least length 2'),
54+
).toBeInTheDocument();
55+
expect(handleSubmit).not.toHaveBeenCalled();
56+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { type } from 'arktype';
2+
import { Field, InternalFieldName } from 'react-hook-form';
3+
4+
export const schema = type({
5+
username: 'string>2',
6+
password: '/.*[A-Za-z].*/>8|/.*\\d.*/',
7+
repeatPassword: 'string>1',
8+
accessToken: 'string|number',
9+
birthYear: '1900<number<2013',
10+
email: 'string.email',
11+
tags: 'string[]',
12+
enabled: 'boolean',
13+
url: 'string>1',
14+
'like?': type({
15+
id: 'number',
16+
name: 'string>3',
17+
}).array(),
18+
dateStr: 'Date',
19+
});
20+
21+
export const validData: typeof schema.infer = {
22+
username: 'Doe',
23+
password: 'Password123_',
24+
repeatPassword: 'Password123_',
25+
birthYear: 2000,
26+
email: 'john@doe.com',
27+
tags: ['tag1', 'tag2'],
28+
enabled: true,
29+
accessToken: 'accessToken',
30+
url: 'https://react-hook-form.com/',
31+
like: [
32+
{
33+
id: 1,
34+
name: 'name',
35+
},
36+
],
37+
dateStr: new Date('2020-01-01'),
38+
};
39+
40+
export const invalidData = {
41+
password: '___',
42+
email: '',
43+
birthYear: 'birthYear',
44+
like: [{ id: 'z' }],
45+
url: 'abc',
46+
};
47+
48+
export const fields: Record<InternalFieldName, Field['_f']> = {
49+
username: {
50+
ref: { name: 'username' },
51+
name: 'username',
52+
},
53+
password: {
54+
ref: { name: 'password' },
55+
name: 'password',
56+
},
57+
email: {
58+
ref: { name: 'email' },
59+
name: 'email',
60+
},
61+
birthday: {
62+
ref: { name: 'birthday' },
63+
name: 'birthday',
64+
},
65+
};

0 commit comments

Comments
 (0)