In search of a perfect and simple form validation library I found two. It is so easy to get thing done with Formik, but there is also a plan B which simpler than I think.
React Hook Form
This is another form validation library for React developers to make interative forms with ease. The getStarted guide so simple to follow.
Dependency
npm install react-hook-form
We can destructure register, handleSubmit from the useForm hook.
const { register, handleSubmit } = useForm();
Register
The register can be used to register the input. Validation can be passed as the second parameter the register function.
<input {...register("exampleRequired", { required: true })} />
It can be a complex validation as follows
<input {...register("firstName", { required: true, maxLength: 20 })} />
<input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
<input type="number" {...register("age", { min: 18, max: 99 })} />
handleSubmit
This can be used to implement our submit logic function
The complete sample
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName", { required: true, maxLength: 20 })} />
<input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
<input type="number" {...register("age", { min: 18, max: 99 })} />
<input type="submit" />
</form>
);
}
So I can focus on another component , no worries about Forms and validation
- How to setup Formik in Reactjs
- Resetting Formik form in Reactjs
- Yup validation schema in Formik
- React Prismic CMS slice
- React Custom Hook for data validation
- React local storage hook
- Too many re-render in error in React hook
- How to enable validation on visited fields in Formik
- React Hook Form that can simplify form validation
- Integrate Formik validation with Mui Form in React