DEV Community

Cover image for React Form Conditional Validation with Formik and Yup (Custom Hooks)
Ch Usama
Ch Usama

Posted on

React Form Conditional Validation with Formik and Yup (Custom Hooks)

In this article, you will fastly start using Formik and Yup(Conditional) with custom hooks in your React project.


Formik is using for building forms in React. Formik is providing lots of feature (less code, easy maintable, custom hooks, easy integrate and more)that making life easier while creating forms. You can easily build schema for validation with Yup.

Installing Formik

npm i formik

Installing Yup

npm i yup

Introduction of Formik

  1. Getting values in and out of form state
  2. Validation and error messages
  3. Handling form submission
// Simple form with formik
import React from "react";
import { useFormik } from "formik";
const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      email: "",
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="email">Email Address</label>
      <button type="submit">Submit</button>
Enter fullscreen mode Exit fullscreen mode

Problem statement

The problem is that formik form has two inputs. One is select and other is text input select has two option 'yes' or 'no'. If user select the 'Yes' then user must write about the dish on the other hand if user select the 'no' there is no validation.


I had a formik form where I needed to enter the passphrase if it was required and make it optional if it wasn't required. While validating the field using 'Yup' I needed a way to conditionally change the validation logic for the field. For this, I need to use the when() function from Yup which allows us to change the validation logic applied to a field based on some conditions. After this I pass the values with and make condition that if user select the Yes (User want to eat chicken)from the option then user must write about chicken dishes which one user want otherwise no condition. Write about the dish depend on the user selection.

Formik useFormik custom hook

const formik = useFormik({
  initialValues: {
  dropdown: "",
  ChickenDish: "",
Enter fullscreen mode Exit fullscreen mode

Yup Schema

validationSchema: Yup.object({
  dropdown: Yup.string(),
  ChickenDish: Yup.string().when("dropdown", {
   is: (dropdown) => dropdown === "Yes",
  then: Yup.string().required("* Required"),
Enter fullscreen mode Exit fullscreen mode


Top comments (0)