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:
- 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>
- Install
class-validator
,@hookform/resolvers
andclass-transformer
packages. Define class for your form fields, register your resolver with the form More info
npm i class-transformer @hookform/resolvers class-validator
class User {
@MaxLength(20)
@IsNotEmpty()
firstName: string;
@IsNotEmpty()
lastName: string;
@IsNumber()
age: number;
}
const resolver = classValidatorResolver(User);
const formMethods = useForm<User>({ resolver });
- Add following properties under
compilerOptions
intsconfig.json
"strictPropertyInitialization": false,
"experimentalDecorators": true
- 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
- 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
]
}
- Additionally, if there's this error:
TypeError: Reflect.metadata is not a function
, installreflect-metadata
withnpm i reflect-metadata
and import it at your app root.
Top comments (0)