React Hook Form Resolvers

repository·master·Indexed 25 days ago

https://github.com/react-hook-form/resolvers

A collection of validation schema resolvers for React Hook Form that enable integration with popular schema validation libraries, including Zod, Yup, Joi, Superstruct, Vest, Class Validator, io-ts, Nope, computed-types, TypeBox, arktype, Typanion, Effect-TS, VineJS, Ajv, and ata-validator.

Tokens
9K
Snippets
23
Records
49
Agent score
80%

What's inside @hookform/resolvers

  1. Use VineJS resolver with React Hook Form

    master

    Integrate VineJS using vineResolver.

    import { useForm } from 'react-hook-form';
    import { vineResolver } from '@hookform/resolvers/vine';
    import vine from '@vinejs/vine';
    
    const schema = vine.compile(
      vine.object({
        username: vine.string().minLength(1),
        password: vine.string().minLength(1),
      }),
    );
    
    const App = () => {
      const { register, handleSubmit } = useForm({
        resolver: vineResolver(schema),
      });
    
      return (
        <form onSubmit={handleSubmit((d) => console.log(d))}>
          <input {...register('username')} />
          <input {...register('password')} />
          <input type="submit" />
        </form>
      );
    };
  2. Use ArkType resolver with React Hook Form

    master

    Integrate ArkType using arktypeResolver.

    import { useForm } from 'react-hook-form';
    import { arktypeResolver } from '@hookform/resolvers/arktype';
    import { type } from 'arktype';
    
    const schema = type({
      username: 'string>1',
      password: 'string>1',
    });
    
    const App = () => {
      const { register, handleSubmit } = useForm({
        resolver: arktypeResolver(schema),
      });
    
      return (
        <form onSubmit={handleSubmit((d) => console.log(d))}>
          <input {...register('username')} />
          <input {...register('password')} />
          <input type="submit" />
        </form>
      );
    };
  3. Use Typanion resolver with React Hook Form

    master

    Integrate typanion using typanionResolver.

    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')} />
          <input type="submit" />
        </form>
      );
    };
  4. Create an Ajv resolver with ajvResolver

    master

    Use ajvResolver to integrate Ajv schema validation with react-hook-form. The resolver accepts an Ajv schema, schema options for the Ajv instance, and resolver options to control validation behavior.

    Parameters

    • schema: The Ajv schema object to validate against.
    • schemaOptions: (Optional) Additional options passed to the Ajv constructor (e.g., allErrors, coerceTypes).
    • resolverOptions: (Optional) Configuration for the resolver.
      • mode: Set to 'async' to enable Ajv's asynchronous validation mode ($async: true).

    Usage

    import { useForm } from 'react-hook-form';
    import { ajvResolver } from '@hookform/resolvers/ajv';
    import Ajv from 'ajv';
    
    const ajv = new Ajv();
    const schema = ajv.compile({
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'number' }
      }
    });
    
    const { register, handleSubmit } = useForm({
      resolver: ajvResolver(schema)
    });
    const schema = ajv.compile({
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'number' }
      }
    });
    
    useForm({
      resolver: ajvResolver(schema)
    });
  5. Use fluentValidationResolver for synchronous validation

    master

    Use fluentValidationResolver to integrate fluentvalidation-ts synchronous validators with react-hook-form. Pass an instance of a Validator class to the function to create a compatible resolver.

    import { Validator } from 'fluentvalidation-ts';
    import { fluentValidationResolver } from '@hookform/resolvers/fluentvalidation-ts';
    import { useForm } from 'react-hook-form';
    
    class SchemaValidator extends Validator<Schema> {
      constructor() {
        super();
        this.ruleFor('username').notEmpty();
        this.ruleFor('password').notEmpty();
      }
    }
    
    const validator = new SchemaValidator();
    
    const { register, handleSubmit } = useForm({
      resolver: fluentValidationResolver(validator)
    });
    import { Validator } from 'fluentvalidation-ts';
    
    class SchemaValidator extends Validator<Schema> {
      constructor() {
        super();
        this.ruleFor('username').notEmpty();
        this.ruleFor('password').notEmpty();
      }
    }
    
    const validator = new SchemaValidator();
    
    useForm({
      resolver: fluentValidationResolver(validator)
    });
  6. Create a resolver with typeschemaResolver

    master

    The typeschemaResolver function creates a react-hook-form compatible resolver using a schema that implements the StandardSchemaV1 specification.

    It accepts a schema and an optional resolverOptions object. If resolverOptions.raw is set to true, the resolver returns the original input values instead of the parsed/transformed output values.

    Parameters

    • schema: A StandardSchemaV1 compliant schema.
    • resolverOptions (optional):
      • raw: A boolean. If true, the resolver returns the input values as they are. If false (default), it returns the validated/transformed output from the schema.
    const schema = z.object({
      name: z.string().required(),
      age: z.number().required(),
    });
    
    useForm({
      resolver: typeschemaResolver(schema)
    });
  7. Ata-validator resolver type definitions

    master

    When building or using a custom resolver for ata-validator with react-hook-form, the resolver follows a specific functional signature. It is a higher-order function that accepts a schema and optional validator options, returning a function compatible with react-hook-form's resolver interface.

    Resolver Signature

    A Resolver is defined as:

    (schema, schemaOptions?, resolverOptions?) => (values, context, options) => Promise<ResolverResult>
    • schema: An object representing the validation schema.
    • schemaOptions: Optional ValidatorOptions from ata-validator.
    • resolverOptions: An object that can include a raw boolean flag.
    • values: The form values to validate.
    • context: Optional context passed from react-hook-form.
    • options: ResolverOptions from react-hook-form.

    Error Types

    Validation errors returned by the resolver use the AtaValidationError type, which is an alias for ValidationError from the ata-validator package.

    export type Resolver = (
      schema: object,
      schemaOptions?: ValidatorOptions,
      resolverOptions?: {
        raw?: boolean;
      },
    ) => <TFieldValues extends FieldValues, TContext>(
      values: TFieldValues,
      context: TContext | undefined,
      options: ResolverOptions<TFieldValues>,
    ) => Promise<ResolverResult<TFieldValues>>;
    
    export type AtaValidationError = ValidationError;
  8. Use the Effect-ts resolver

    master
    The @hookform/resolvers/effect-ts package provides a resolver for use with react-hook-form that integrates with the Effect-ts library. It allows you to use Effect schemas to validate form data. To use it, import the resolver from the effect-ts entrypoint and pass it to the resolver option in useForm.
  9. Use the Zod resolver with React Hook Form

    master
    The Zod resolver allows you to use Zod schemas for validation within react-hook-form. You can import the resolver from @hookform/resolvers/zod and pass it to the resolver property of the useForm hook. This enables seamless integration between your Zod validation logic and React Hook Form's state management.