DEV Community

Elizabeth Sobiya
Elizabeth Sobiya

Posted on

Getting Started with Yup Validations in React: A Beginner's Guide

Hey there, fellow developers! 👋 If you've been working with forms in React, you know how tedious validation can get. But fear not! Today, we're diving into Yup, a JavaScript schema builder for value parsing and validation. Yup makes form validation in React a breeze. Let’s break it down step-by-step in a beginner-friendly way.

What is Yup?

Yup is a JavaScript library that helps you define and validate data schemas. Think of it as a tool that ensures the data your forms receive is exactly as expected. Whether you need to check if an email is valid or if a password meets certain criteria, Yup has you covered.

Why Use Yup?

  • Simplicity: Define complex validation logic with straightforward, readable code.
  • Integration: Works seamlessly with form libraries like Formik.
  • Flexibility: Easily create custom validation methods.

Installing Yup

First things first, let’s get Yup installed in your React project. You can do this using npm or yarn:

npm install yup
Enter fullscreen mode Exit fullscreen mode

or

yarn add yup
Enter fullscreen mode Exit fullscreen mode

Basic Usage of Yup

Let’s start with a simple example to understand how Yup works. Suppose we have a form where we need to validate an email and a password.

Step 1: Import Yup

In your React component, import Yup:

import * as Yup from 'yup';
Enter fullscreen mode Exit fullscreen mode

Step 2: Define Your Schema

Next, define a validation schema for your form data. Here’s an example:

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'),
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Validate Data

Now, you can use this schema to validate your form data. Here’s a basic example:

const formData = {
  email: 'user@example.com',
  password: 'password123',
};

validationSchema
  .validate(formData)
  .then((valid) => {
    console.log('Validation passed:', valid);
  })
  .catch((error) => {
    console.log('Validation failed:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Using Yup with Formik

Formik is a popular library for managing form state in React. Yup integrates beautifully with Formik, making form validation even simpler.

Step 1: Install Formik

First, install Formik:

npm install formik
Enter fullscreen mode Exit fullscreen mode

or

yarn add formik
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Form with Formik and Yup

Here’s a complete example of how to use Formik with Yup for form validation:

import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const SignupSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
  password: Yup.string().min(6, 'Password too short').required('Required'),
});

const MyForm = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{ email: '', password: '' }}
      validationSchema={SignupSchema}
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <div>
            <label>Email</label>
            <Field name="email" type="email" />
            <ErrorMessage name="email" component="div" />
          </div>

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

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

export default MyForm;
Enter fullscreen mode Exit fullscreen mode

In this example, we:

  1. Define the Schema: Using Yup, we define the rules for the email and password fields.
  2. Setup Formik: We initialize Formik with the schema and initial values.
  3. Render the Form: We use Formik’s components to create the form, displaying validation errors using ErrorMessage.

Real-World Use Cases for Yup

1. User Registration Forms

When registering users, it’s essential to validate their input. Yup can ensure the email is valid, the password meets complexity requirements, and usernames are not empty.

const registrationSchema = Yup.object().shape({
  username: Yup.string().required('Username 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'),
});
Enter fullscreen mode Exit fullscreen mode

2. Complex Nested Forms

Yup can handle nested objects and arrays, making it perfect for forms that require detailed and complex validation.

const profileSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  address: Yup.object().shape({
    street: Yup.string().required('Street is required'),
    city: Yup.string().required('City is required'),
    zip: Yup.string().required('ZIP code is required'),
  }),
});
Enter fullscreen mode Exit fullscreen mode

3. Custom Validation Logic

Sometimes, you need custom validation. Yup allows you to create your own validation methods.

const customSchema = Yup.object().shape({
  username: Yup.string().test('is-john-doe', 'Username cannot be John Doe', (value) => value !== 'John Doe'),
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Yup is a powerful library that makes form validation in React straightforward and efficient. By defining schemas and integrating with libraries like Formik, you can ensure that your forms are reliable and user-friendly.

I hope this guide helps you get started with Yup. Happy coding! If you have any questions or need further clarification, feel free to ask in the comments below.

Top comments (0)