Schema-Based Form Validation in React.js
There are several libraries in the market, that can provide React.js projects with the schema-based form validation.
The top three of them are: Zod, Joi, and Yup.
In this post, I am going to describe one of the best called "Zod".
This library, at the moment, has more than 6M weekly downloads in NPM.
With Zod, we can define a validation schema as follows:
const schema = z.object({
name: z.string().min(3),
age: z.number().min(18),
});
By using Zod schema, we no longer need to define an interface like this:
interface FormData {
name: string;
age: number;
}
We can extract the type of the form fields by using infer like this:
type FormData = z.infer<typeof schema>;
For connection of the zod schema to "react-hook-form" we need to install resolvers like this:
yarn add @hookform/resolvers
To use it in our component, first, we need to import the zodResolver:
import { zodResolver } from "@hookform/resolvers/zod";
领英推荐
Note that, if you are using other libraries for form validation, such as Yup or Joi, the import statements are similar:
import { yupResolver } from '@hookform/resolvers/yup';
import { joiResolver } from '@hookform/resolvers/joi';
Next, we have to define it as the useForm hook config:
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({ resolver: zodResolver(schema) });
And finally, the form input and its validation error message can be like this:
<input
type="text"
className="form-control"
id="name"
{...register("name")}
/>
{errors.name && <p className="text-danger">{errors.name.message}</p>}
Thanks for reading this article.
For more information, please refer to:
#Joi #Zod #Yup #typescript #form_validation #react_hook_form
Frontend Developer | React.js, Next.js | JavaScript, TypeScript
1 年References of the article: https://www.npmjs.com/package/yup https://joi.dev/api/ https://www.npmjs.com/package/zod