Formik is a popular form management library in React, and it can be integrated with Next.js for handling form validation. Below are the steps to handle form validation in Next.js using Formik:
Install Formik and Yup: Install Formik and Yup for validation by running the following commands:
bashnpm install formik yup
or
bashyarn add formik yup
Create a Form Component: Create a new component for your form. This component will use Formik for managing the form state and validation.
jsx// components/MyForm.js
import { useFormik } from 'formik';
import * as Yup from 'yup';
const MyForm = () => {
const formik = useFormik({
initialValues: {
// Define your form fields and initial values
email: '',
password: '',
},
validationSchema: Yup.object({
// Define validation rules using Yup
email: Yup.string().email('Invalid email address').required('Required'),
password: Yup.string().required('Required'),
}),
onSubmit: values => {
// Handle form submission
console.log(values);
},
});
return (
<form onSubmit={formik.handleSubmit}>
{/* Email Input */}
<label htmlFor="email">Email:</label>
<input
id="email"
name="email"
type="text"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.email}
/>
{formik.touched.email && formik.errors.email && <div>{formik.errors.email}</div>}
{/* Password Input */}
<label htmlFor="password">Password:</label>
<input
id="password"
name="password"
type="password"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.password}
/>
{formik.touched.password && formik.errors.password && <div>{formik.errors.password}</div>}
{/* Submit Button */}
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
Use the Form Component in a Next.js Page: Now, you can use this form component in a Next.js page.
jsx// pages/index.js
import MyForm from '../components/MyForm';
const Home = () => {
return (
<div>
<h1>My Next.js Form</h1>
<MyForm />
</div>
);
};
export default Home;
When you run your Next.js app and navigate to the specified page, you should see the form with validation working.
Optional: Style your form: You can style your form using CSS or a styling solution of your choice.
That's it! You've now set up form validation in Next.js using Formik and Yup. Customize the form fields, validation rules, and submission logic according to your specific requirements.