Convert Figma logo to code with AI

react-hook-form logoresolvers

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS

1,754
159
1,754
45

Top Related Projects

22,814

Dead simple Object schema validation

33,503

TypeScript-first schema validation with static type inference

A simple and composable way to validate data in JavaScript (and TypeScript).

Decorator-based property validation for classes.

20,860

The most powerful data validation library for JS

13,713

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)

Quick Overview

React Hook Form Resolvers is a library that provides integration between React Hook Form and popular validation libraries. It offers a seamless way to use various schema validation libraries with React Hook Form, enhancing form validation capabilities in React applications.

Pros

  • Simplifies integration of validation libraries with React Hook Form
  • Supports multiple popular validation libraries (Yup, Zod, Joi, etc.)
  • Improves code organization and maintainability
  • Reduces boilerplate code for form validation

Cons

  • Adds an additional dependency to the project
  • May have a slight learning curve for developers new to schema validation
  • Limited to the supported validation libraries
  • Potential performance impact for very complex forms

Code Examples

  1. Using Yup for validation:
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';

const schema = yup.object({
  name: yup.string().required(),
  age: yup.number().positive().integer().required(),
}).required();

const { register, handleSubmit, formState: { errors } } = useForm({
  resolver: yupResolver(schema)
});
  1. Using Zod for validation:
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
});

const { register, handleSubmit, formState: { errors } } = useForm({
  resolver: zodResolver(schema)
});
  1. Using Joi for validation:
import { useForm } from 'react-hook-form';
import { joiResolver } from '@hookform/resolvers/joi';
import Joi from 'joi';

const schema = Joi.object({
  username: Joi.string().alphanum().min(3).max(30).required(),
  password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
});

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

Getting Started

  1. Install the necessary packages:

    npm install react-hook-form @hookform/resolvers yup
    
  2. Import and use the resolver in your component:

    import { useForm } from 'react-hook-form';
    import { yupResolver } from '@hookform/resolvers/yup';
    import * as yup from 'yup';
    
    const schema = yup.object({
      name: yup.string().required(),
      email: yup.string().email().required(),
    }).required();
    
    const { register, handleSubmit, formState: { errors } } = useForm({
      resolver: yupResolver(schema)
    });
    
    const onSubmit = data => console.log(data);
    
    return (
      <form onSubmit={handleSubmit(onSubmit)}>
        <input {...register("name")} />
        <input {...register("email")} />
        <input type="submit" />
      </form>
    );
    

Competitor Comparisons

22,814

Dead simple Object schema validation

Pros of Yup

  • More mature and widely adopted library with a larger ecosystem
  • Supports a broader range of validation scenarios beyond form validation
  • Offers a more flexible and extensible API for complex validation rules

Cons of Yup

  • Larger bundle size, which may impact performance in smaller projects
  • Steeper learning curve due to its more comprehensive feature set
  • Less tightly integrated with React Hook Form, requiring additional setup

Code Comparison

Yup:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  age: Yup.number().positive().integer().required('Age is required'),
});

Resolvers:

import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

const schema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  age: Yup.number().positive().integer().required('Age is required'),
});

const resolver = yupResolver(schema);

Summary

While Yup offers a more comprehensive validation solution with greater flexibility, Resolvers provides a streamlined integration with React Hook Form. Yup is better suited for complex validation scenarios and projects requiring extensive customization, while Resolvers offers a more straightforward approach for form validation within the React Hook Form ecosystem. The choice between the two depends on the specific needs of your project and your familiarity with each library.

33,503

TypeScript-first schema validation with static type inference

Pros of Zod

  • Standalone schema validation library, usable in various contexts beyond form validation
  • More powerful and flexible type inference capabilities
  • Supports complex data structures and custom validation logic

Cons of Zod

  • Steeper learning curve due to its more comprehensive feature set
  • Larger bundle size compared to the lightweight resolvers library
  • May be overkill for simple form validation use cases

Code Comparison

Zod schema definition:

const schema = z.object({
  name: z.string().min(2),
  age: z.number().min(18),
  email: z.string().email(),
});

React Hook Form resolver using Zod:

import { zodResolver } from "@hookform/resolvers/zod";

useForm({
  resolver: zodResolver(schema),
});

Both libraries can be used together, with Zod providing the schema definition and react-hook-form/resolvers offering integration with React Hook Form. Zod offers a more comprehensive solution for schema validation, while resolvers focuses specifically on integrating various validation libraries with React Hook Form.

The choice between the two depends on the project's requirements. For simple form validation within React Hook Form, resolvers may be sufficient. For more complex validation needs or use cases beyond form validation, Zod provides a more robust solution.

A simple and composable way to validate data in JavaScript (and TypeScript).

Pros of Superstruct

  • More flexible and powerful schema definition capabilities
  • Can be used for general-purpose data validation beyond form handling
  • Supports custom types and complex nested structures

Cons of Superstruct

  • Steeper learning curve due to its more comprehensive feature set
  • Not specifically tailored for React Hook Form integration
  • May require additional setup for use with React Hook Form

Code Comparison

Superstruct schema definition:

import { object, string, number } from 'superstruct'

const User = object({
  name: string(),
  age: number(),
})

Resolvers schema definition:

import * as yup from 'yup'

const schema = yup.object({
  name: yup.string().required(),
  age: yup.number().positive().integer().required(),
})

Both libraries offer powerful validation capabilities, but Superstruct provides a more flexible and extensible system for defining complex data structures. Resolvers, being specifically designed for React Hook Form, offers a more streamlined integration with the form library.

Superstruct excels in scenarios where you need to validate data beyond form submissions, while Resolvers is optimized for form validation within React applications using React Hook Form.

The choice between the two depends on your specific use case and whether you need a general-purpose validation library or a form-specific solution.

Decorator-based property validation for classes.

Pros of class-validator

  • More versatile, can be used in various contexts beyond form validation
  • Extensive set of built-in decorators for common validation scenarios
  • Supports custom validation functions for complex use cases

Cons of class-validator

  • Requires defining separate class structures for validation
  • May have a steeper learning curve for developers new to decorator-based validation
  • Can be more verbose when used specifically for form validation

Code Comparison

class-validator:

import { IsEmail, MinLength } from 'class-validator';

class UserDto {
  @IsEmail()
  email: string;

  @MinLength(8)
  password: string;
}

resolvers (with Yup):

import * as Yup from 'yup';

const schema = Yup.object().shape({
  email: Yup.string().email().required(),
  password: Yup.string().min(8).required(),
});

Summary

class-validator is a powerful and flexible validation library that can be used in various contexts, including form validation. It offers a wide range of built-in decorators and supports custom validation functions. However, it may require more setup and can be more verbose when used specifically for form validation.

resolvers, on the other hand, is designed specifically for integrating validation libraries with react-hook-form. It provides a more streamlined approach to form validation but may be less versatile for other validation scenarios outside of forms.

20,860

The most powerful data validation library for JS

Pros of Joi

  • More comprehensive and flexible validation library
  • Supports a wider range of data types and validation scenarios
  • Can be used independently of any specific framework or library

Cons of Joi

  • Larger bundle size, which may impact performance in client-side applications
  • Steeper learning curve due to its extensive API and features
  • Not specifically optimized for React Hook Form integration

Code Comparison

Joi validation:

const schema = Joi.object({
  username: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().email().required()
});

react-hook-form/resolvers (using Yup):

const schema = yup.object({
  username: yup.string().min(3).max(30).required(),
  email: yup.string().email().required()
});

Summary

Joi is a powerful and versatile validation library that offers extensive features for various use cases. However, react-hook-form/resolvers provides a more streamlined approach specifically tailored for React Hook Form integration. While Joi excels in flexibility and comprehensiveness, react-hook-form/resolvers offers better performance and ease of use within React applications. The choice between the two depends on the specific requirements of your project and the desired balance between functionality and optimization.

13,713

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)

Pros of ajv

  • More comprehensive and flexible JSON schema validation
  • Higher performance, especially for large datasets
  • Supports custom keywords and formats for advanced validation scenarios

Cons of ajv

  • Steeper learning curve due to its extensive feature set
  • Not specifically designed for React form validation
  • Requires more setup and configuration for form-specific use cases

Code Comparison

ajv:

const Ajv = require('ajv');
const ajv = new Ajv();

const schema = {
  type: 'object',
  properties: {
    foo: { type: 'integer' },
    bar: { type: 'string' }
  },
  required: ['foo', 'bar']
};

const validate = ajv.compile(schema);

react-hook-form/resolvers (with Yup):

import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';

const schema = yup.object({
  foo: yup.number().required(),
  bar: yup.string().required()
});

const { register, handleSubmit, errors } = useForm({
  resolver: yupResolver(schema)
});

While ajv provides powerful JSON schema validation, react-hook-form/resolvers offers seamless integration with React Hook Form and various validation libraries. ajv excels in performance and flexibility, but requires more setup for form validation. react-hook-form/resolvers simplifies form validation in React applications, making it more accessible for typical use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Performant, flexible and extensible forms with easy to use validation.

npm downloads npm npm

Install

npm install @hookform/resolvers

Links

Supported resolvers

API

type Options = {
  mode: 'async' | 'sync',
  raw?: boolean
}

resolver(schema: object, schemaOptions?: object, resolverOptions: Options)
typeRequiredDescription
schemaobject✓validation schema
schemaOptionsobjectvalidation library schema options
resolverOptionsobjectresolver options, async is the default mode

Quickstart

Yup

Dead simple Object schema validation.

npm

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(),
  })
  .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>
  );
};

Zod

TypeScript-first schema validation with static type inference

npm

⚠️ Example below uses the valueAsNumber, which requires react-hook-form v6.12.0 (released Nov 28, 2020) or later.

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as 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: 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>
  );
};

Superstruct

A simple and composable way to validate data in JavaScript (or TypeScript).

npm

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

Joi

The most powerful data validation library for JS.

npm

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

Vest

Vest 🦺 Declarative Validation Testing.

npm

import { useForm } from 'react-hook-form';
import { vestResolver } from '@hookform/resolvers/vest';
import { create, test, enforce } from 'vest';

const validationSuite = create((data = {}) => {
  test('username', 'Username is required', () => {
    enforce(data.username).isNotEmpty();
  });

  test('password', 'Password is required', () => {
    enforce(data.password).isNotEmpty();
  });
});

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

Class Validator

Decorator-based property validation for classes.

npm

⚠️ Remember to add these options to your tsconfig.json!

"strictPropertyInitialization": false,
"experimentalDecorators": true
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;

  @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="submit" value="Submit" />
    </form>
  );
};

io-ts

Validate your data with powerful decoders.

npm

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;

Nope

A small, simple, and fast JS validator

npm

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

computed-types

TypeScript-first schema validation with static type inference

npm

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

typanion

Static and runtime type assertion library with no dependencies

npm

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

Ajv

The fastest JSON validator for Node.js and browser

npm

import { useForm } from 'react-hook-form';
import { ajvResolver } from '@hookform/resolvers/ajv';

// must use `minLength: 1` to implement required field
const schema = {
  type: 'object',
  properties: {
    username: {
      type: 'string',
      minLength: 1,
      errorMessage: { minLength: 'username field is required' },
    },
    password: {
      type: 'string',
      minLength: 1,
      errorMessage: { minLength: 'password field is required' },
    },
  },
  required: ['username', 'password'],
  additionalProperties: false,
};

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

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <input {...register('username')} />
      {errors.username && <span>{errors.username.message}</span>}
      <input {...register('password')} />
      {errors.password && <span>{errors.password.message}</span>}
      <button type="submit">submit</button>
    </form>
  );
};

TypeBox

JSON Schema Type Builder with Static Type Resolution for TypeScript

npm

With ValueCheck

import { useForm } from 'react-hook-form';
import { typeboxResolver } from '@hookform/resolvers/typebox';
import { Type } from '@sinclair/typebox';

const schema = Type.Object({
  username: Type.String({ minLength: 1 }),
  password: Type.String({ minLength: 1 }),
});

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

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

With TypeCompiler

A high-performance JIT of TypeBox, read more

import { useForm } from 'react-hook-form';
import { typeboxResolver } from '@hookform/resolvers/typebox';
import { Type } from '@sinclair/typebox';
import { TypeCompiler } from '@sinclair/typebox/compiler';

const schema = Type.Object({
  username: Type.String({ minLength: 1 }),
  password: Type.String({ minLength: 1 }),
});

const typecheck = TypeCompiler.Compile(schema);

const App = () => {
  const { register, handleSubmit } = useForm({
    resolver: typeboxResolver(typecheck),
  });

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

ArkType

TypeScript's 1:1 validator, optimized from editor to runtime

npm

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 type="password" {...register('password')} />
      <input type="submit" />
    </form>
  );
};

Valibot

The modular and type safe schema library for validating structural data

npm

import { useForm } from 'react-hook-form';
import { valibotResolver } from '@hookform/resolvers/valibot';
import * as v from 'valibot';

const schema = v.object({
  username: v.pipe(
    v.string('username is required'),
    v.minLength(3, 'Needs to be at least 3 characters'),
    v.endsWith('cool', 'Needs to end with `cool`'),
  ),
  password: v.string('password is required'),
});

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

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

TypeSchema

Universal adapter for schema validation, compatible with any validation library

npm

import { useForm } from 'react-hook-form';
import { typeschemaResolver } from '@hookform/resolvers/typeschema';
import * as z from 'zod';

// Use your favorite validation library
const schema = z.object({
  username: z.string().min(1, { message: 'Required' }),
  password: z.number().min(1, { message: 'Required' }),
});

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

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

effect-ts

A powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library.

npm

import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '@hookform/resolvers/effect-ts';
import { Schema } from '@effect/schema';

const schema = Schema.Struct({
  username: Schema.String.pipe(
    Schema.nonEmpty({ message: () => 'username required' }),
  ),
  password: Schema.String.pipe(
    Schema.nonEmpty({ message: () => 'password required' }),
  ),
});

type FormData = Schema.Schema.Type<typeof schema>;

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

function TestComponent({ onSubmit }: Props) {
  const {
    register,
    handleSubmit,
    formState: { errors },
    // provide generic if TS has issues inferring types
  } = useForm<FormData>({
    resolver: effectTsResolver(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>
  );
}

VineJS

VineJS is a form data validation library for Node.js

npm

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')} />
      {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>
  );
};

fluentvalidation-ts

A TypeScript-first library for building strongly-typed validation rules

npm

import { useForm } from 'react-hook-form';
import { fluentValidationResolver } from '@hookform/resolvers/fluentvalidation-ts';
import { Validator } from 'fluentvalidation-ts';

class FormDataValidator extends Validator<FormData> {
  constructor() {
    super();

    this.ruleFor('username')
      .notEmpty()
      .withMessage('username is a required field');
    this.ruleFor('password')
      .notEmpty()
      .withMessage('password is a required field');
  }
}

const App = () => {
  const { register, handleSubmit } = useForm({
    resolver: fluentValidationResolver(new FormDataValidator()),
  });

  return (
    <form onSubmit={handleSubmit((d) => console.log(d))}>
      <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>
  );
};

Backers

Thanks go to all our backers! [Become a backer].

Contributors

Thanks go to these wonderful people! [Become a contributor].

NPM DownloadsLast 30 Days