Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(standard-schema): add standard-schema resolver #738

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Install your preferred validation library alongside `@hookform/resolvers`.
- [effect-ts](#effect-ts)
- [VineJS](#vinejs)
- [fluentvalidation-ts](#fluentvalidation-ts)
- [standard-schema](#standard-schema)
- [Backers](#backers)
- [Sponsors](#sponsors)
- [Contributors](#contributors)
Expand Down Expand Up @@ -779,6 +780,72 @@ const App = () => {
};
```

### [standard-schema](https://github.com/standard-schema/standard-schema)

A standard interface for TypeScript schema validation libraries

[![npm](https://img.shields.io/bundlephobia/minzip/@standard-schema/spec?style=for-the-badge)](https://bundlephobia.com/result?p=@standard-schema/spec)

Example zod

```typescript jsx
import { useForm } from 'react-hook-form';
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
import { z } from 'zod';

const schema = z.object({
name: z.string().min(1, { message: 'Required' }),
age: z.number().min(10),
});

const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: standardSchemaResolver(schema),
});

return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```

Example arkType

```typescript jsx
import { useForm } from 'react-hook-form';
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
import { type } from 'arktype';

const schema = type({
username: 'string>1',
password: 'string>1',
});

const App = () => {
const { register, handleSubmit } = useForm({
resolver: standardSchemaResolver(schema),
});

return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```

## Backers

Thanks go to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
Expand Down
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions config/node-13-exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const subRepositories = [
'effect-ts',
'vine',
'fluentvalidation-ts',
'standard-schema',
];

const copySrc = () => {
Expand Down
2 changes: 1 addition & 1 deletion effect-ts/src/effect-ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { Effect } from 'effect';

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

export const effectTsResolver: Resolver =
Expand Down
16 changes: 14 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@
"import": "./fluentvalidation-ts/dist/fluentvalidation-ts.mjs",
"require": "./fluentvalidation-ts/dist/fluentvalidation-ts.js"
},
"./standard-schema": {
"types": "./standard-schema/dist/index.d.ts",
"umd": "./standard-schema/dist/standard-schema.umd.js",
"import": "./standard-schema/dist/standard-schema.mjs",
"require": "./standard-schema/dist/standard-schema.js"
},
"./package.json": "./package.json",
"./*": "./*"
},
Expand Down Expand Up @@ -184,7 +190,10 @@
"vine/dist",
"fluentvalidation-ts/package.json",
"fluentvalidation-ts/src",
"fluentvalidation-ts/dist"
"fluentvalidation-ts/dist",
"standard-schema/package.json",
"standard-schema/src",
"standard-schema/dist"
],
"publishConfig": {
"access": "public"
Expand All @@ -211,6 +220,7 @@
"build:effect-ts": "microbundle --cwd effect-ts --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,effect=Effect,effect/SchemaAST=EffectSchemaAST,effect/ParseResult=EffectParseResult",
"build:vine": "microbundle --cwd vine --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@vinejs/vine=vine",
"build:fluentvalidation-ts": "microbundle --cwd fluentvalidation-ts --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm",
"build:standard-schema": "microbundle --cwd standard-schema --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@standard-schema/spec=standardSchema",
"postbuild": "node ./config/node-13-exports.js && check-export-map",
"lint": "bunx @biomejs/biome check --write --vcs-use-ignore-file=true .",
"lint:types": "tsc",
Expand Down Expand Up @@ -243,7 +253,8 @@
"arktype",
"typeschema",
"vine",
"fluentvalidation-ts"
"fluentvalidation-ts",
"standard-schema"
],
"repository": {
"type": "git",
Expand All @@ -257,6 +268,7 @@
"homepage": "https://react-hook-form.com",
"devDependencies": {
"@sinclair/typebox": "^0.34.15",
"@standard-schema/spec": "^1.0.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
Expand Down
18 changes: 18 additions & 0 deletions standard-schema/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@hookform/resolvers/standard-schema",
"amdName": "hookformResolversStandardSchema",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: standard-schema",
"main": "dist/standard-schema.js",
"module": "dist/standard-schema.module.js",
"umd:main": "dist/standard-schema.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@standard-schema/spec": "^1.0.0",
"@hookform/resolvers": "^2.0.0"
}
}
82 changes: 82 additions & 0 deletions standard-schema/src/__tests__/Form-native-validation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { type } from 'arktype';
import React from 'react';
import { useForm } from 'react-hook-form';
import { standardSchemaResolver } from '..';

const schema = type({
username: 'string>1',
password: 'string>1',
});

type FormData = typeof schema.infer;

interface Props {
onSubmit: (data: FormData) => void;
}

function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: standardSchemaResolver(schema),
shouldUseNativeValidation: true,
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />

<input {...register('password')} placeholder="password" />

<button type="submit">submit</button>
</form>
);
}

test("form's native validation with arkType", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');

await user.click(screen.getByText(/submit/i));

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(
'username must be at least length 2',
);

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'password must be at least length 2',
);

await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});
56 changes: 56 additions & 0 deletions standard-schema/src/__tests__/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { type } from 'arktype';
import React from 'react';
import { useForm } from 'react-hook-form';
import { standardSchemaResolver } from '..';

const schema = type({
username: 'string>1',
password: 'string>1',
});

type FormData = typeof schema.infer & { unusedProperty: string };

interface Props {
onSubmit: (data: FormData) => void;
}

function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: standardSchemaResolver(schema), // Useful to check TypeScript regressions
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}

<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}

<button type="submit">submit</button>
</form>
);
}

test("form's validation with arkType and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

expect(screen.queryAllByRole('alert')).toHaveLength(0);

await user.click(screen.getByText(/submit/i));

expect(
screen.getByText('username must be at least length 2'),
).toBeInTheDocument();
expect(
screen.getByText('password must be at least length 2'),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
65 changes: 65 additions & 0 deletions standard-schema/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { type } from 'arktype';
import { Field, InternalFieldName } from 'react-hook-form';

export const schema = type({
username: 'string>2',
password: '/.*[A-Za-z].*/>8|/.*\\d.*/',
repeatPassword: 'string>1',
accessToken: 'string|number',
birthYear: '1900<number<2013',
email: 'string.email',
tags: 'string[]',
enabled: 'boolean',
url: 'string>1',
'like?': type({
id: 'number',
name: 'string>3',
}).array(),
dateStr: 'Date',
});

export const validData: typeof schema.infer = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
url: 'https://react-hook-form.com/',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: new Date('2020-01-01'),
};

export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
};

export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};
Loading