form with formik and yup react js

Form with Formik and Yup in React JS

Formik is a popular library in React JS that helps in managing form state and validation. Yup is a library that provides a simple way to validate objects. Together, Formik and Yup make form validation much easier in React JS.

Installation

You can install Formik and Yup by running the following commands in the terminal:

$ npm install formik yup

Usage

First, import the necessary libraries:

// Import libraries
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

Then, define the validation schema using Yup:

// Define validation schema
const validationSchema = Yup.object().shape({
  name: Yup.string()
    .min(2, 'Name must be at least 2 characters.')
    .max(50, 'Name must be at most 50 characters.')
    .required('Name is required.'),
  email: Yup.string()
    .email('Invalid email.')
    .required('Email is required.'),
  password: Yup.string()
    .min(8, 'Password must be at least 8 characters.')
    .required('Password is required.'),
});

Then, define the form using Formik:

// Define form
const form = (
  <Formik
    initialValues={{
      name: '',
      email: '',
      password: '',
    }}
    onSubmit={values => {
      console.log(values);
    }}
    validationSchema={validationSchema}
  >
    {({ errors, touched }) => (
      <Form>
        <div>
          <label htmlFor="name">Name</label>
          <Field name="name" />
          <ErrorMessage name="name" />
        </div>

        <div>
          <label htmlFor="email">Email</label>
          <Field name="email" />
          <ErrorMessage name="email" />
        </div>

        <div>
          <label htmlFor="password">Password</label>
          <Field name="password" type="password" />
          <ErrorMessage name="password" />
        </div>

        <button type="submit">Submit</button>
      </Form>
    )}
  </Formik>
);

The form contains three fields: name, email, and password. Each field has a label, a Field component, and an ErrorMessage component. The onSubmit function is called when the form is submitted, and the values of the fields are logged to the console. The validationSchema is used to validate the values of the fields.

Alternative Approach

Another way to use Formik and Yup is to define the form as a separate component:

// Define form component
const MyForm = () => (
  <Formik
    initialValues={{
      name: '',
      email: '',
      password: '',
    }}
    onSubmit={values => {
      console.log(values);
    }}
    validationSchema={validationSchema}
  >
    {({ errors, touched }) => (
      <Form>
        <div>
          <label htmlFor="name">Name</label>
          <Field name="name" />
          <ErrorMessage name="name" />
        </div>

        <div>
          <label htmlFor="email">Email</label>
          <Field name="email" />
          <ErrorMessage name="email" />
        </div>

        <div>
          <label htmlFor="password">Password</label>
          <Field name="password" type="password" />
          <ErrorMessage name="password" />
        </div>

        <button type="submit">Submit</button>
      </Form>
    )}
  </Formik>
);

// Use form component
const App = () => (
  <div>
    <MyForm />
  </div>
);

In this approach, the form is defined as a separate component, which can be used in any other component.

Conclusion

Formik and Yup make form validation easy in React JS. By defining the validation schema using Yup and using Formik to manage the form state and validation, you can create forms quickly and easily.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe