DEV Community

Cover image for How to Create and Validate Forms in React using Formik and Yup
Rajiv Chaulagain
Rajiv Chaulagain

Posted on

3

How to Create and Validate Forms in React using Formik and Yup

Validating form using state and managing data of form is like a hell and repetition , so Using formik and yup helps and is easy to work with formik.

So starting with formik and yup ,
use npm i formik yup to install it in your environment

Now , I will show a code that uses less boilerplate and is easy to use.

Now I will create a component as App.js

import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from 'yup'
const profileSchema = Yup.object().shape({
Firstname: Yup.string()
.min(3, "Minimum 3 symbols")
.max(50, "Maximum 50 symbols")
.required("First name is required")};
const App = () => {
const onFormSubmit = async (value) => {
console.log({value});
};
const initialValues = {
Firstname: ''
};
return (
<Formik
validationSchema={profileSchema}
initialValues={initialValues}
onSubmit={onFormSubmit}
>
{({ touched, dirty, isValid }) => (
<Form className="">
<div
className="form-group col-md-6"
>
<label className="required" htmFor="FirstName">First Name</label>
<Field
type="text"
name="Firstname"
id="Firstname"
className="form-control"
placeholder="First Name"
required
/>
<div className="text-danger">
<ErrorMessage name="Firstname" />
</div>
</div>
<button
type="submit"
id="kt_sign_in_submit animate.css"
className="btn btn-md btn-primary w-10 mt-4"
disabled={touched && !dirty && !isValid}
>
<span
className="indicator-progress"
style={{ display: "block" }}
>
Click me!
<span className="spinner-border spinner-border-sm align-middle ms-2"></span>
</span>
</button>
</For>
)}
</Formik>
)}
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay