To add validation with `Yup` in combination with `react-hook-form`, you'll need to install both `yup` and `@hookform/resolvers`:
```bash
npm install yup @hookform/resolvers
```
Here's how you can use `Yup` for schema validation in your form:
1. **Import Necessary Libraries**: Import `useForm` from `react-hook-form` and `yup` for validation schema creation.
2. **Create a Validation Schema**: Use `Yup` to create a validation schema.
3. **Connect the Schema to `react-hook-form`**: Use `@hookform/resolvers/yup` to integrate the schema with `react-hook-form`.
Below is the updated example:
```jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
// Define the validation schema using Yup
const schema = yup.object().shape({
name: yup.string().required('Name is required'),
email: yup.string().email('Invalid email address').required('Email is required'),
password: yup.string().min(6, 'Password must be at least 6 characters long').required('Password is required'),
});
const SimpleFormWithYup = () => {
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: yupResolver(schema),
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="name">Name</label>
<input
id="name"
{...register('name')}
/>
{errors.name && <p>{errors.name.message}</p>}
</div>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
{...register('email')}
/>
{errors.email && <p>{errors.email.message}</p>}
</div>
<div>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
{...register('password')}
/>
{errors.password && <p>{errors.password.message}</p>}
</div>
<button type="submit">Submit</button>
</form>
);
};
export default SimpleFormWithYup;
```
### Explanation:
1. **Validation Schema**:
- We define a validation schema using `yup.object().shape()` to specify the validation rules.
- Each field (`name`, `email`, `password`) has its own validation rules.
2. **Use `yupResolver`**:
- The `yupResolver` from `@hookform/resolvers/yup` is used to integrate `Yup` with `react-hook-form`.
3. **Form Configuration**:
- `useForm` is called with an object containing the `resolver` property set to `yupResolver(schema)`.
- This tells `react-hook-form` to use the validation schema defined with `Yup`.
4. **Error Messages**:
- The errors from validation are displayed next to the corresponding fields.
This setup ensures that the form validation logic is cleanly separated from the component logic, making the code more maintainable and scalable.