DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

Using class-validator with Next.js and react-hook-form

Let's use class-validator as a validation library with react-hook-form. I found using class-validator with Next.js a bit tricky as it uses decorators for validations and setting it up is a bit involved and took me quite some time to make it work. Link to Stackblitz

Steps:

  1. Create your form with react-hook-form More info
<form>
    <input {...register('firstName')} />
    {errors.firstName && <div>{errors.firstName.message}</div>}

    <input {...register('lastName')} />
    {errors.lastName && <div>{errors.lastName.message}</div>}

    <input type="number" {...register('age')} />
    {errors.age && <div>{errors.age.message}</div>}

    <input type="submit" value="Submit" />
</form>
Enter fullscreen mode Exit fullscreen mode
  1. Install class-validator, @hookform/resolvers and class-transformer packages. Define class for your form fields, register your resolver with the form More info
npm i class-transformer @hookform/resolvers class-validator
Enter fullscreen mode Exit fullscreen mode
class User {
  @MaxLength(20)
  @IsNotEmpty()
  firstName: string;

  @IsNotEmpty()
  lastName: string;

  @IsNumber()
  age: number;
}

const resolver = classValidatorResolver(User);

const formMethods = useForm<User>({ resolver });
Enter fullscreen mode Exit fullscreen mode
  1. Add following properties under compilerOptions in tsconfig.json
"strictPropertyInitialization": false,
"experimentalDecorators": true
Enter fullscreen mode Exit fullscreen mode
  1. Install the following packages More info
npm install --save-dev @babel/core babel-plugin-transform-typescript-metadata @babel/plugin-proposal-decorators babel-plugin-parameter-decorator
Enter fullscreen mode Exit fullscreen mode
  1. Update the list of plugins in .babelrc as follows:
{
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "babel-plugin-parameter-decorator",
    // ... other plugins
  ]
}
Enter fullscreen mode Exit fullscreen mode
  1. Additionally, if there's this error: TypeError: Reflect.metadata is not a function, install reflect-metadata with npm i reflect-metadata and import it at your app root.

More info here and here

Top comments (0)