Sometimes, we want to validate input values with React.
In this article, we’ll look at how to validate input values with React.
Validate Input Values with React
To validate input values with React, we can use the react-hook-form
library.
To install it, we run:
npm i react-hook-form
Then we can use it by writing:
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const {
register,
handleSubmit,
watch,
formState: { errors }
} = useForm();
const onSubmit = (data) => console.log(data);
console.log(watch("name"));
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input defaultValue="jane" {...register("firstName")} />
<input {...register("lastName", { required: true })} />
{errors.lastName && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
We call the useForm
hook to return an object with various properties.
And we use the register
function to register the fields so that react-hook-form can do validation on the field.
We pass in the name of the field and an object with the validation options of the field.
To make a field required, we set the required
property to true
.
Then we can show the errors from the errors
object.
The onSubmit
function is the function that runs when the form values are all valid.
We call handleSubmit
with onSubmit
so that it only runs when the form values are valid.
handleSubmit
returns a function that we can use as the event handler for the submit event of a form.
Now when we click Submit without the lastName
field filled out, we should see an error message displayed.
Conclusion
To validate input values with React, we can use the react-hook-form
library.