Skip to content

feat: add new resolver @badrap/valita #756

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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
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
33 changes: 33 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`.
| vine | ✅ | `firstError | all` |
| yup | ✅ | `firstError | all` |
| zod | ✅ | `firstError | all` |
| valita | ❌ | `firstError` |
</details>

## TypeScript
Expand Down Expand Up @@ -117,6 +118,7 @@ useForm<z.input<typeof schema>, any, z.output<typeof schema>>({
- [VineJS](#vinejs)
- [fluentvalidation-ts](#fluentvalidation-ts)
- [standard-schema](#standard-schema)
- [valita](#valita)
- [Backers](#backers)
- [Sponsors](#sponsors)
- [Contributors](#contributors)
Expand Down Expand Up @@ -909,6 +911,37 @@ const App = () => {
};
```

### [valita](https://github.com/badrap/valita)

A typesafe validation & parsing library for TypeScript.

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

```typescript jsx
import { useForm } from 'react-hook-form';
import { valitaResolver } from '@hookform/resolvers/valita';
import * as v from '@badrap/valita';

const schema = v.object({
username: v.string(),
password: v.string(),
});

const App = () => {
const { register, handleSubmit } = useForm({
resolver: valitaResolver(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
3 changes: 3 additions & 0 deletions bun.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
},
"devDependencies": {
"@sinclair/typebox": "^0.34.30",
"@badrap/valita": "^0.4.3",
"@standard-schema/spec": "^1.0.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
Expand Down Expand Up @@ -274,6 +275,8 @@

"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-H45s8fVLYjbhFH62dIJ3WtmJ6RSPt/3DRO0ZcT2SUiYiQyz3BLVb9ADEnLl91m74aQPS3AzzeajZHYOalWe3bg=="],

"@badrap/valita": ["@badrap/[email protected]", "", {}, "sha512-C9iZSrVlTb610dxZ2oatK5LwefaHv0Q9eYfVDH3co846x7WinhCfc8jCDTE55yM8WxlmOfX2ckKmsSr7KzZ/gg=="],

"@csstools/color-helpers": ["@csstools/[email protected]", "", {}, "sha512-JqWH1vsgdGcw2RR6VliXXdA0/59LttzlU8UlRT/iUUsEeWfYq8I+K0yhihEUTTHLRm1EXvpsCx3083EU15ecsA=="],

"@csstools/css-calc": ["@csstools/[email protected]", "", { "peerDependencies": { "@csstools/css-parser-algorithms": "^3.0.4", "@csstools/css-tokenizer": "^3.0.3" } }, "sha512-TklMyb3uBB28b5uQdxjReG4L80NxAqgrECqLZFQbyLekwwlcDDS8r3f07DKqeo8C4926Br0gf/ZDe17Zv4wIuw=="],
Expand Down
1 change: 1 addition & 0 deletions config/node-13-exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const subRepositories = [
'vine',
'fluentvalidation-ts',
'standard-schema',
'valita',
];

const copySrc = () => {
Expand Down
16 changes: 14 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,12 @@
"import": "./standard-schema/dist/standard-schema.mjs",
"require": "./standard-schema/dist/standard-schema.js"
},
"./valita": {
"types": "./valita/dist/index.d.ts",
"umd": "./valita/dist/valita.umd.js",
"import": "./valita/dist/valita.mjs",
"require": "./valita/dist/valita.js"
},
"./package.json": "./package.json",
"./*": "./*"
},
Expand Down Expand Up @@ -193,7 +199,10 @@
"fluentvalidation-ts/dist",
"standard-schema/package.json",
"standard-schema/src",
"standard-schema/dist"
"standard-schema/dist",
"valita/package.json",
"valita/src",
"valita/dist"
],
"publishConfig": {
"access": "public"
Expand Down Expand Up @@ -221,6 +230,7 @@
"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",
"build:valita": "microbundle --cwd valita --globals @hookform/resolvers=hookformResolvers,react-hook-form=ReactHookForm,@badrap/valita=valita",
"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 @@ -254,7 +264,8 @@
"typeschema",
"vine",
"fluentvalidation-ts",
"standard-schema"
"standard-schema",
"valita"
],
"repository": {
"type": "git",
Expand All @@ -268,6 +279,7 @@
"homepage": "https://react-hook-form.com",
"devDependencies": {
"@sinclair/typebox": "^0.34.30",
"@badrap/valita": "^0.4.3",
"@standard-schema/spec": "^1.0.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
Expand Down
18 changes: 18 additions & 0 deletions valita/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@hookform/resolvers/valita",
"amdName": "hookformResolversValita",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: valita",
"main": "dist/valita.js",
"module": "dist/valita.module.js",
"umd:main": "dist/valita.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"@badrap/valita": "0.4.x",
"@hookform/resolvers": "^2.0.0",
"react-hook-form": "^7.0.0"
}
}
100 changes: 100 additions & 0 deletions valita/src/__tests__/Form-native-validation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import * as v from '@badrap/valita';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { useForm } from 'react-hook-form';
import { valitaResolver } from '..';

const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const USERNAME_LENGTH_TOO_SHORT = 'username is too short';

function strRequired(message: string) {
return (value: string) => {
if (value === '') {
return v.err(message);
}
return v.ok(value);
};
}

function strMinLength(min: number) {
return (value: string) => {
if (value.length < min) {
return v.err(USERNAME_LENGTH_TOO_SHORT);
}
return v.ok(value);
};
}

const schema = v.object({
username: v
.string()
.chain(strRequired(USERNAME_REQUIRED_MESSAGE))
.chain(strMinLength(2)),
password: v
.string()
.chain(strRequired(PASSWORD_REQUIRED_MESSAGE))
.chain(strMinLength(2)),
});

type FormData = { username: string; password: string };

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

function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: valitaResolver(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 valita", 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_REQUIRED_MESSAGE);

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);

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

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

const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const USERNAME_LENGTH_TOO_SHORT = 'username is too short';

function strRequired(message: string) {
return (value: string) => {
if (value === '') {
return v.err(message);
}
return v.ok(value);
};
}

function strMinLength(min: number) {
return (value: string) => {
if (value.length < min) {
return v.err(USERNAME_LENGTH_TOO_SHORT);
}
return v.ok(value);
};
}

const schema = v.object({
username: v
.string()
.chain(strRequired(USERNAME_REQUIRED_MESSAGE))
.chain(strMinLength(2)),
password: v
.string()
.chain(strRequired(PASSWORD_REQUIRED_MESSAGE))
.chain(strMinLength(2)),
});

type FormData = { username: string; password: string };

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

function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: valitaResolver(schema),
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="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>
);
}

describe('valita form validation errors', () => {
test('ensure custom validation messages are shown', async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

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

await user.type(screen.getByPlaceholderText('username'), 'a');
await user.click(screen.getByText(/submit/i));

expect(screen.getByText(/username is too short/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
});

export function TestComponentManualType({
onSubmit,
}: {
onSubmit: (data: FormData) => void;
}) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<v.Infer<typeof schema>, undefined, FormData>({
resolver: valitaResolver(schema),
});

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>
);
}
Loading