Posted by
The Code Post
on
- Get link
- X
- Other Apps
What are Formik and Yup?
What is Formik?
Formik is a library that simplifies the management of form components. It is used to manage user inputs, error messages, and the overall form state (e.g., whether it has been submitted or is valid). Formik automatically tracks and controls the form's state and validity.
What is Yup?
Yup is a schema validation library for JavaScript. When used with Formik, it can be used to validate user inputs. With Yup, you can define which fields are required, how to validate certain formats, and more.
Simple Example
Below, we will create a simple form using Formik and Yup. The form will have an email and a password field, and these fields will be subject to validation rules.
Installing the Required Packages
npm install formik yup
Example Code
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const MyForm = () => {
const validationSchema = Yup.object().shape({
email: Yup.string()
.email('Invalid email address')
.required('Email is required'),
password: Yup.string()
.min(6, 'Password must be at least 6 characters')
.required('Password is required'),
});
return (
<Formik
initialValues={{ email: '', password: '' }}
validationSchema={validationSchema}
onSubmit={(values) => {
console.log('Form values:', values);
}}
>
{() => (
<Form>
<div>
<label htmlFor="email">Email:</label>
<Field name="email" type="email" />
<ErrorMessage name="email" component="div" />
</div>
<div>
<label htmlFor="password">Password:</label>
<Field name="password" type="password" />
<ErrorMessage name="password" component="div" />
</div>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
};
export default MyForm;
Explanation
- Importing Formik and Yup: We import the Formik and Yup libraries.
- Validation Schema: We define a
validationSchemausing Yup. For theemailfield, we specify a valid email format, and for thepasswordfield, we require a minimum of 6 characters. - Using Formik: We create the form using the Formik component. The
initialValuesprop is used to define the initial values of the form fields. - Field and ErrorMessage: We define the form fields and error messages. The
Fieldcomponent represents the form fields, while theErrorMessagecomponent is used to display validation error messages. - Submit Handler: When the form is submitted, the
onSubmitfunction is triggered and logs the form values to the console.
This example demonstrates the basics of creating a simple form using Formik and Yup. You can add more fields and extend the validation rules to suit your needs.
Comments
Post a Comment