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
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.