Validation of a Formik form using Yup in React

Key takeaways

  • Formik offers a seamless way to handle form state, submission, and user interactions. When combined with Yup, the validation logic becomes declarative, making it easy to define consistent rules and reuse them across multiple forms.

  • Formik’s validate function gives developers full control over the validation process, which is useful for dynamic forms, cross-field validation, and asynchronous scenarios.

  • Using a Yup schema allows developers to define all validation rules in a single place, improving code readability and maintainability. This declarative style ensures validation logic is easy to modify and reuse across multiple forms, making the development process more efficient.

  • Formik supports field-level validation that ensures that only the relevant fields are validated as users interact with them, minimizing unnecessary re-renders and improving the form's responsiveness.

  • Using resetForm() to clear inputs after a successful submission ensures a smooth user experience, especially for multi-step or frequently submitted forms. Providing instant validation feedback with <ErrorMessage> improves usability and guides users towards successful submission.

Form validation with Formik and Yup

In React applications, using Formik and Yup significantly enhances form validation. Formik streamlines the management of form states, validations, and submissions, reducing the need for redundant code. Concurrently, Yup empowers developers to create precise and readable validation schemas, improving code maintainability. By adopting these libraries, developers ensure their applications adhere to best practices in form handling, from simple input requirements like username length to complex validation logic.

Formik's validate property and the useFormik hook

The validate property in Formik allows us to define custom validation logic using a function. When using validate, the user is responsible for writing the validation rules within this function. This benefits more complex or dynamic validation scenarios where we need more control over the validation process. For instance, conditional validations or asynchronous validation can be handled within the validate function.

Following is the structure of using validate with the useFormik hook.

const formik = useFormik({
initialValues: {
// Initial values for the form fields
},
validate: (values) => {
// Custom validation logic
// Return errors for invalid fields
},
});
Formik setup with custom validation logic

In the following code, we have made a basic form with fields of name, email, and age.

Here’s an explanation of the React component code using Formik and validate for custom validation:

  • Lines 1–2: The code begins by importing React and the useFormik hook from Formik, setting up the necessary React component and form management tools.

  • Line 4: The ContactUsWithValidation function component is defined, utilizing useFormik to initialize the form’s state and behavior.

  • Lines 5–10: Inside useFormik, initialValues are set, establishing the starting state for the form fields name, email, and age.

  • Lines 15–42: The validate function defines validation logic for each form field. For the name field, it checks if the field is empty and does not contain numbers. The email field validation ensures the input is not empty and conforms to a valid email format, utilizing a regular expression. Similarly, the age field is checked for nonemptiness, numeric value, and a specific age range (15-60). If any field fails its validation, an appropriate error message is added to the errors object, which Formik uses to manage and display errors.

  • Lines 46–96: The onSubmit handler function captures and processes user input when the form is submitted, displaying the values in a console log and an alert. This section also constructs the form's interface, including input fields for name, email, and age, each equipped with conditional logic to show relevant validation messages. Additionally, a submit button is integrated, enabling users to submit their input and showcasing a user-friendly and interactive form experience.

  • Line 100: The form is wrapped up, and the component is exported, making it available for use elsewhere in the application.

Practice advanced React concepts by attempting this project, Build an Image Sharing App with MERN Stack.

Using Yup to define the validation schema

Alternatively, Formik provides the validationSchema property to define validation rules using an external validation schema library like Yup. Yup provides a declarative way to define validation rules using schema validation.

The validationSchema property allows to integration of Yup’s schema into Formik, making it simpler to define validation rules using Yup’s validation methods. This approach is great for static or standard validation requirements as it provides a clear and structured way to define validation rules outside of the form component.

Following is the structure of using validationSchema.

<Formik
initialValues={{
// Initial values for the form fields
}}
validationSchema=validationSchema
>
Formik setup with Yup validation schema

In the following code, we have used the same project as above with validate replace with validationSchema, which is using Yup.

Here’s an explanation of the React component code using Formik and Yup for validation:

  • Lines 1–3: These lines import the necessary modules: React, Formik components, and Yup for defining validation schemas.

  • Lines 6–15: The ContactUsWithValidation function initializes a Yup validation schema, which defines the validation rules for the name, email, and age fields. Specifically, name must be a string without numbers and is required, email must be a string in a valid email format and is required, and age must be a number within the range of 15 to 60 and is also required. This schema ensures that each field adheres to these specific validation criteria before the form can be successfully submitted.

  • Lines 18–26: Initialize Formik using <Formik> element, setting initialValues for form fields, defining an onSubmit function to handle form submissions and link the validationSchema.

  • Lines 27–47: The JSX structure constructs the form, setting up fields for name, email, and age. The <Field> component simplifies managing field values, and <ErrorMessage> displays validation errors. This ensures users receive immediate feedback on their input, enhancing the form’s usability and interactivity.

Want to use Formik and Yup to build real world applications? Try this project out, Build a Resume Builder in React Using Redux.

In conclusion, Yup proves to be a helpful library that simplifies user validation rules. However, in the case of custom validation, especially cross-field validation validate is preferred. Nonetheless, when it comes to custom validation, particularly cross-field validation, using the validate method is preferred.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the difference between using validate and validationSchema in Formik?

The validate function is used to write custom validation logic, typically for dynamic or complex scenarios, such as cross-field validation or conditional checks. On the other hand, validationSchema uses Yup to define rules declaratively, which is easier to maintain and reuse for standard validations.


What are the advantages of using <Field> and <ErrorMessage> components in Formik?

<Field> simplifies input management by automatically binding values and handlers to the form state, reducing the need for repetitive code. <ErrorMessage> makes error handling easier by displaying validation feedback without requiring additional logic.


How can I improve the performance of forms built with Formik?

For large forms, enabling field-level validation ensures only the affected fields are validated when users interact with them, reducing unnecessary re-renders.


What is the difference between YUP and Formik?

Formik is a library for managing form state, validation, and submission in React, while Yup is a schema validation library used with Formik to validate form inputs using declarative rules.


What is Formik in React JS?

ormik is a library for managing forms in React, handling form state, validation, and submission, making it easier to work with forms and reducing boilerplate code.



Free Resources

Copyright ©2025 Educative, Inc. All rights reserved