Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
@hookform/resolvers
Advanced tools
React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types and Typanion
The @hookform/resolvers package is used in conjunction with React Hook Form to integrate external validation libraries. It provides resolvers that allow you to use your preferred validation schema with React Hook Form, ensuring that form data adheres to certain rules before it is processed or submitted.
Yup Resolver
Integrates Yup validation schema with React Hook Form.
{"import { yupResolver } from '@hookform/resolvers/yup';\nimport * as yup from 'yup';\n\nconst schema = yup.object().shape({\n name: yup.string().required(),\n age: yup.number().positive().integer().required(),\n});\n\nconst { register, handleSubmit, errors } = useForm({\n resolver: yupResolver(schema)\n});\n\n// In your form...\n<input name='name' ref={register} />\n<p>{errors.name?.message}</p>\n<input name='age' ref={register} />\n<p>{errors.age?.message}</p>"}
Joi Resolver
Integrates Joi validation schema with React Hook Form.
{"import { joiResolver } from '@hookform/resolvers/joi';\nimport Joi from 'joi';\n\nconst schema = Joi.object({\n username: Joi.string().alphanum().min(3).max(30).required(),\n password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),\n});\n\nconst { register, handleSubmit, errors } = useForm({\n resolver: joiResolver(schema)\n});\n\n// In your form...\n<input name='username' ref={register} />\n<p>{errors.username?.message}</p>\n<input name='password' ref={register} />\n<p>{errors.password?.message}</p>"}
Zod Resolver
Integrates Zod validation schema with React Hook Form.
{"import { zodResolver } from '@hookform/resolvers/zod';\nimport { z } from 'zod';\n\nconst schema = z.object({\n firstName: z.string().min(1, { message: 'First name is required' }),\n age: z.number().min(10, { message: 'Minimum age is 10' }),\n});\n\nconst { register, handleSubmit, errors } = useForm({\n resolver: zodResolver(schema)\n});\n\n// In your form...\n<input name='firstName' ref={register} />\n<p>{errors.firstName?.message}</p>\n<input name='age' ref={register} />\n<p>{errors.age?.message}</p>"}
React Hook Form is the core library that @hookform/resolvers is designed to work with. It provides a way to manage forms with minimal re-rendering, but it does not include built-in schema-based validation. @hookform/resolvers complements it by adding this capability.
Formik is another popular form management library for React. It handles form state, validation, and submission. Unlike React Hook Form, Formik includes built-in support for Yup validation without needing an additional resolver package.
Redux Form is a form library that works with Redux for state management. It includes validation functionalities but is generally considered heavier and more complex than React Hook Form and requires Redux to be part of the project.
Performant, flexible and extensible forms with easy to use validation.
$ npm install @hookform/resolvers
resolver(schema: object, schemaOptions?: object, resolverOptions: { mode: 'async' | 'sync' })
type | Required | Description | |
---|---|---|---|
schema | object | ✓ | validation schema |
schemaOptions | object | validation library schema options | |
resolverOptions | object | resolver options, async is the default mode |
Dead simple Object schema validation.
import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
const schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: yupResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
export default App;
TypeScript-first schema validation with static type inference
⚠️ Example below uses the
valueAsNumber
, which requiresreact-hook-form
v6.12.0 (released Nov 28, 2020) or later.
import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
const schema = z.object({
name: z.string().nonempty({ message: 'Required' }),
age: z.number().min(10),
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(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>
);
};
export default App;
A simple and composable way to validate data in JavaScript (or TypeScript).
import React from 'react';
import { useForm } from 'react-hook-form';
import { superstructResolver } from '@hookform/resolvers/superstruct';
import { object, string, number } from 'superstruct';
const schema = object({
name: string(),
age: number(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: superstructResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age', { valueAsNumber: true })} />
<input type="submit" />
</form>
);
};
export default App;
The most powerful data validation library for JS.
import React from 'react';
import { useForm } from 'react-hook-form';
import { joiResolver } from '@hookform/resolvers/joi';
import Joi from 'joi';
const schema = Joi.object({
name: Joi.string().required(),
age: Joi.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: joiResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
export default App;
Vest 🦺 Declarative Validation Testing.
import * as React from 'react';
import { useForm } from 'react-hook-form';
import { vestResolver } from '@hookform/resolvers/vest';
import vest, { test, enforce } from 'vest';
const validationSuite = vest.create((data = {}) => {
test('username', 'Username is required', () => {
enforce(data.username).isNotEmpty();
});
test('username', 'Must be longer than 3 chars', () => {
enforce(data.username).longerThan(3);
});
test('password', 'Password is required', () => {
enforce(data.password).isNotEmpty();
});
test('password', 'Password must be at least 5 chars', () => {
enforce(data.password).longerThanOrEquals(5);
});
test('password', 'Password must contain a digit', () => {
enforce(data.password).matches(/[0-9]/);
});
test('password', 'Password must contain a symbol', () => {
enforce(data.password).matches(/[^A-Za-z0-9]/);
});
});
const App = () => {
const { register, handleSubmit, errors } = useForm({
resolver: vestResolver(validationSuite),
});
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
export default App;
Decorator-based property validation for classes.
⚠️ Remember to add these options to your
tsconfig.json
!
"strictPropertyInitialization": false,
"experimentalDecorators": true
import React from 'react';
import { useForm } from 'react-hook-form';
import { classValidatorResolver } from '@hookform/resolvers/class-validator';
import { Length, Min, IsEmail } from 'class-validator';
class User {
@Length(2, 30)
username: string;
@Min(18)
age: number;
@IsEmail()
email: string;
}
const resolver = classValidatorResolver(User);
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<User>({ resolver });
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input type="text" {...register('username')} />
{errors.username && <span>{errors.username.message}</span>}
<input type="text" {...register('email')} />
{errors.email && <span>{errors.email.message}</span>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age && <span>{errors.age.message}</span>}
<input type="submit" value="Submit" />
</form>
);
};
export default App;
Validate your data with powerful decoders.
import React from 'react';
import { useForm } from 'react-hook-form';
import { ioTsResolver } from '@hookform/resolvers/io-ts';
import t from 'io-ts';
// you don't have to use io-ts-types but it's very useful
import tt from 'io-ts-types';
const schema = t.type({
username: t.string,
age: tt.NumberFromString,
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: ioTsResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
export default App;
A small, simple, and fast JS validator
import React from 'react';
import { useForm } from 'react-hook-form';
import { nopeResolver } from '@hookform/resolvers/nope';
import Nope from 'nope-validator';
const schema = Nope.object().shape({
name: Nope.string().required(),
age: Nope.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: nopeResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
export default App;
TypeScript-first schema validation with static type inference
import React from 'react';
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '@hookform/resolvers/computed-types';
import Schema, { number, string } from 'computed-types';
const schema = Schema({
username: string.min(1).error('username field is required'),
age: number,
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: computedTypesResolver(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>
);
};
export default App;
Static and runtime type assertion library with no dependencies
import React from 'react';
import { useForm } from 'react-hook-form';
import { typanionResolver } from '@hookform/resolvers/typanion';
import * as t from 'typanion';
const isUser = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
age: t.applyCascade(t.isNumber(), [t.isInteger(), t.isInInclusiveRange(1, 100)]),
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: typanionResolver(isUser),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age')} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
export default App;
Thanks goes to all our backers! [Become a backer].
Thanks goes to these wonderful organizations! [Contribute].
Thanks goes to these wonderful people! [Become a contributor].
FAQs
React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types, TypeBox, arktype, Typanion, Effect-TS and VineJS
The npm package @hookform/resolvers receives a total of 3,142,605 weekly downloads. As such, @hookform/resolvers popularity was classified as popular.
We found that @hookform/resolvers demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.