Table of contents
Using Form validation is a critical part of web development to ensure that the user submits the right input. In React, we have different libraries to handle form validation, such as yup
and React Hook Forms
. In this article, we'll look at how to integrate yup
with React Hook Forms
to create a dynamic form validation process.
What is yup
?
yup
is a JavaScript schema validation library that provides a simple and easy way to validate objects, strings, and numbers. It's lightweight and works with all JavaScript environments, including React.
What is React Hook Forms
?
React Hook Forms
is a library for managing forms in React, allowing developers to create flexible and performant forms using hooks.
Getting started
npm install yup react-hook-form
Next, let's create a simple form with React Hook Forms
.
import React from 'react';
import { useForm } from 'react-hook-form';
function App() {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" name="name" ref={register} />
<button type="submit">Submit</button>
</form>
);
}
export default App;
This form includes a single input field for the user's name and a submit button. When the form is submitted, it logs the input data to the console.
Integrating yup
Now, let's integrate yup
with React Hook Forms
. We will define a schema using yup
and use it to validate the form input.
import React from 'react';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';
const schema = yup.object().shape({
name: yup.string().required(),
});
function App() {
const { register, handleSubmit, errors } = useForm({
validationSchema: schema,
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" name="name" ref={register} />
{errors.name && <p>{errors.name.message}</p>}
<button type="submit">Submit</button>
</form>
);
}
export default App;
In this updated code, we first import yup
and define a schema object that specifies the validation rules for the form. In this case, the schema requires the name
field to be a non-empty string.
We then pass the schema object to useForm
as the validationSchema
option, which tells React Hook Forms
to use yup
for validation.
Finally, we render the form input and conditionally render an error message if there is an error with the name
field. The error message is taken from the message
property of the yup
validation error object.
If you found this article useful, please consider following me for more such content. You can also subscribe to my newsletter to stay updated on my latest articles, tutorials, and projects. Thank you for reading!