React simple form Validation using Formik and Yup

0

Hello guys, Welcome back with React Form Validation with Formik and Yup. In my case, I was validating the form using states and with conditions. It's easy to confirm a few inputs, but if it goes to more inputs fields. We cannot use state conditions because it will cover more lines in your codes.

Why have I started to use React Formik and Yup validation?

When I used React Formik the first time, it was tricky to work with it. But after a second time while using it was an essential Package in my project.

And one of my friends recommended using React for form validation in react. That was the plus point to using React Formik. It is easy to work on React Formik at any of my react projects.

Let's get started with React Formik and Yup Form Validation.

For using React Formik and Yup validation. Firstly, you need to install both packages from NPM. You can easily install React Formik and Yup from executing the below command.

If you are using Yarn

yarn add formik yup

If you are using NPM

npm install formik yup

Basic React Formik Validation with Yup.

Here it's an example for basic Formik and Yup Validation. Let's get started.

import React from 'react'

import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";

export default function FormikValidation() {

    const LoginSchema = Yup.object().shape({
        email: Yup.string()
          .email("Invalid email address format")
          .required("Email is required"),
        password: Yup.string()
          .min(8, "Password must be 8 characters at minimum")
          .required("Password is required"),
      });


    return (
        <>
            

            <div className="container">
                <h3 className="my-4 text-center">Log In Form Validation</h3>
                <div className="row">
                    <div className="col-lg-6 offset-lg-3">

                    <Formik

                        initialValues={{ 
                            email: "", 
                            password: "" 
                        }}
                        validationSchema={LoginSchema}
                        onSubmit={(values) => {
                            console.log(values);
                            
                        }}
                        >
                        {(props) => (
                            <Form>
                                <div className="form-group">
                                    <label htmlFor="Email ID">Email</label>
                                    <Field type="email" 
                                        name="email"
                                        className={`form-control ${props.touched.email && props.errors.email ? "is-invalid" : ""} `}
                                        placeholder="Enter your Email"/>

                                    <ErrorMessage
                                        component="div"
                                        name="email"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Password">Password</label>
                                    <Field 
                                        name="password" 
                                        type={"password"} 
                                        className={`form-control ${props.touched.password && props.errors.password ? "is-invalid" : ""} `} 
                                        placeholder="Enter Password"/>

                                        <ErrorMessage
                                            component="div"
                                            name="password"
                                            className="invalid-feedback"
                                            />
                                </div>

                                <div className="my-3 text-center">
                                    <button type="submit" className="btn btn-primary btn-block py-2"> Log In</button>
                                </div> 
                    
                            </Form> 
                        )}
                    </Formik>

                    </div>
                </div>
            </div>
        </>
    )
}

Let me explain the above code. First of all, I have imported Formik, Form, Field, ErrorMessage from Formik and imported all from Yup.

It is a function base component. I have created a const LoginSchema which will help us validate. All the conditions we will write here for validation.

If all conditions are okay, then the onSubmit function will work. Otherwise, it will show the message if any have. I think it's clear to understand.

React Formik and Yup validation for confirm password.

Sometimes it is confusing to validate passwords and confirm passwords using React Formik. For that, the below schema will use to validate passwords and confirm passwords.

const LoginSchema = Yup.object().shape({
        email: Yup.string()
          .email("Invalid email address format")
          .required("Email is required"),
        password: Yup.string()
          .min(8, "Password must be 8 characters at minimum")
          .required("Password is required"),
        cPassword: Yup.string()
        .required('Confirm Password is required')
        .oneOf([Yup.ref('password'), null], 'Passwords must match')
      });

React Formik with confirm password

import React from 'react'

import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";

export default function FormikValidation() {

    const LoginSchema = Yup.object().shape({
        email: Yup.string()
          .email("Invalid email address format")
          .required("Email is required"),
        password: Yup.string()
          .min(8, "Password must be 8 characters at minimum")
          .required("Password is required"),
        cPassword: Yup.string()
        .required('Confirm Password is required')
        .oneOf([Yup.ref('password'), null], 'Passwords must match')
      });


    return (
        <>
            

            <div className="container">
                <h3 className="my-4 text-center">Log In Form Validation</h3>
                <div className="row">
                    <div className="col-lg-6 offset-lg-3">

                    <Formik

                        initialValues={{ 
                            email: "", 
                            password: "" 
                        }}
                        validationSchema={LoginSchema}
                        onSubmit={(values) => {
                            console.log(values);
                            
                        }}
                        >
                        {(props) => (
                            <Form>
                                <div className="form-group">
                                    <label htmlFor="Email ID">Email</label>
                                    <Field type="email" 
                                        name="email"
                                        className={`form-control ${props.touched.email && props.errors.email ? "is-invalid" : ""} `}
                                        placeholder="Enter your Email"/>

                                    <ErrorMessage
                                        component="div"
                                        name="email"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Password">Password</label>
                                    <Field 
                                        name="password" 
                                        type="password"
                                        className={`form-control ${props.touched.password && props.errors.password ? "is-invalid" : ""} `} 
                                        placeholder="Enter Password"/>

                                    <ErrorMessage
                                        component="div"
                                        name="password"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Password">Confirm Password</label>
                                    <Field 
                                        name="cPassword" 
                                        type="password" 
                                        className={`form-control ${props.touched.cPassword && props.errors.cPassword ? "is-invalid" : ""} `} 
                                        placeholder="Enter Password"/>

                                    <ErrorMessage
                                        component="div"
                                        name="cPassword"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="my-3 text-center">
                                    <button type="submit" className="btn btn-primary btn-block py-2"> Log In</button>
                                </div> 
                    
                            </Form> 
                        )}
                    </Formik>

                    </div>
                </div>
            </div>
        </>
    )
}

React Formik and Yup validation for phone number.

Validating phone numbers is the most necessary thing in React Formik validation. For validating phone numbers React, we will use regex for the validation schema. It's the last thing which I thought to share with you.

const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/

	//this will be written in validation schema
	phone: Yup.string()
        .required("Phone Number is required")
        .matches(phoneRegExp, 'Phone Number is not valid')
        .min(10, "Phone Number must have 10 digits")
        .max(10, "Phone Number must have 10 digits"),

I have also shared a video on React Formik and Yup validation.

I hope it was helpful for you and you enjoyed it. This blog helps you to learn new things here.

I hope this was an interesting and full of information article. I hope you liked it.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !