Formik Validation in React

  • By Sarika Ganesh Kore
  • October 23, 2023
  • JavaScript
Formik Validation in React

Formik Validation in React

Handling forms in React applications can be a daunting task. From user input validation to managing form state, there are numerous challenges to overcome. Fortunately, libraries like Formik make this process much more manageable by providing a robust solution for form handling and validation. In this blog post, we’ll explore Formik validation in React.

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

 

What is Formik?

Formik is a popular library for handling forms in React applications. It provides a set of high-level abstractions and utilities to streamline the process of building and validating forms. With Formik, you can manage form state, handle user input, and perform validation with ease.

Setting Up Formik

Before we dive into the details of form validation, let’s set up Formik in a React project. You can install Formik and its dependency Yup (a schema validation library) using npm or yarn:

 

npm install formik yup 

yarn add formik yup 

Now, let’s create a simple form component that uses Formik for validation.

 

import React from ‘react’; 

import { Formik, Field, Form, ErrorMessage } from ‘formik’;

import * as Yup from ‘yup’; 

const initialValues = { name: ”, email: ”, }; 

const validationSchema = Yup.object({ 

name: Yup.string().required(‘Name is required’), 

email: Yup.string().email(‘Invalid email format’).required(‘Email is required’), }); 

function MyForm() 

{ const handleSubmit = (values) => { 

// Handle form submission here 

console.log(values);

 }

return ( 

<Formik initialValues={initialValues} validationSchema={validationSchema} 

onSubmit={handleSubmit} > 

<Form> 

<div> 

<label htmlFor=”name”>Name</label> 

<Field type=”text” id=”name” name=”name” /> 

<ErrorMessage name=”name” component=”div” className=”error” /> </div>

 <div> 

<label htmlFor=”email”>Email</label> 

<Field type=”text” id=”email” name=”email” /> 

<ErrorMessage name=”email” component=”div” className=”error” /> </div> 

<button type=”submit”>Submit</button> 

</Form> 

</Formik> ); 

export default MyForm; 

In the code above, we’ve defined a simple form component that utilizes Formik. Are you looking to enhance your skills in web development with React JS? Look no further! We are excited to offer React JS classes in Pune! Here’s a breakdown of the key components:

  • Formik: This is the top-level component that wraps the form. It takes initialValues, validationSchema, and an onSubmit handler as props.
  • Field: This component is used to render form inputs. It automatically handles value binding and user input.
  • ErrorMessage: This component displays validation errors if any occur.
  • validationSchema: We define a Yup validation schema to specify the validation rules for each form field.
  • onSubmit: This function is called when the form is submitted, and it receives the form values as its argument.

 

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

 

Form Validation Made Easy

Formik simplifies form validation by integrating seamlessly with Yup. Yup allows you to define validation rules declaratively, making it easy to enforce constraints on user input.

In the example above, we’ve defined validation rules for the name and email fields. If a user enters invalid data, such as an empty name or an email with an incorrect format, Formik will handle the validation and display error messages automatically.

Handling Form State

One of the primary challenges when working with forms in React is managing form state. Formik takes care of this by providing an intuitive way to access and manipulate form values.

You can access the current form values using values in your form component and update them using the setValues function if needed.

 

function MyForm() 

const handleSubmit = (values, { setSubmitting }) => 

// Handle form submission here 

console.log(values); 

setSubmitting(false); 

// Reset the submitting state 

}; 

return ( <Formik initialValues={initialValues} validationSchema={validationSchema} 

onSubmit={handleSubmit} > 

{({ isSubmitting }) => ( <Form> 

{/* Form fields go here */} 

<button type=”submit” disabled={isSubmitting}> Submit </button> </Form> )}

 </Formik> );

 } 

 

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

 

In this example, we’ve disabled the “Submit” button when the form is submitted to prevent multiple submissions. Become a React JS Pro with Our React JS Training in Pune. Master Dynamic Web Development. Expert-Led Training. 

Do visit our channel to explore more: Click Here

Conclusion

Form validation in React can be complex, but libraries like Formik simplify the process significantly. By integrating with Yup for declarative validation and providing an easy way to manage form state, Formik streamlines the development of forms in your React applications. Whether you’re building a simple contact form or a complex multi-step wizard, Formik is a valuable tool that can save you time and effort in handling forms.

 

Author:-

Sarika Ganesh Kore

Call the Trainer and Book your free demo Class For React JS Call now!!!
| SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*