Top 4 Libraries for Form Validation in React JS

  • react-js
  • 99 Views
  • 7 Min Read
  • 5 May 2024

Hy coder! Are you building a React application and need to add form validation? Do not worry; we have got you covered. In this article, I'll walk you through the top 4 React form validation libraries: React Hook Form, Formik, Yup, and Final Form. We will break down each library so you can choose the best one for your project.

 

So let's get started!

 

 

The Top 4 Form Validation Libraries

 

  1. React Hook Form
  2. Formik
  3. Yup
  4. Final Form

 

 

1. React Hook From

 
React Hook Form makes managing forms in ReactJs easier by efficiently handling state and validation with minimal code. Using this, we can enhance the user experience and code maintainability.


Why should we use the React Hook Form?

 
React Hook Forms makes it easier for developers to create forms. With its help, we can further enhance the user experience. Today, this library is the most popular for handling forms in React apps.
 
Enjoy simplified form management, high performance, flexible validation, a lightweight structure, and strong community support with React Hook Form.
 
React Hook Form also works with React Native. Although it is primarily designed for React web apps, you can modify it for React Native projects. But keep in mind that some functions might operate differently or require additional configuration due to platform variations.

Weekly downloads via npm: 3m - 4m
 
npm install react-hook-form
 
We can create this kind of form.
 
JSX Code
 
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import "./FormComponent.css";

function App() {
    const { register, handleSubmit, formState: { errors: error } } = useForm({});
    const [submitted, setSubmitted] = useState(false);

    const onSubmit = (data, e) => {
        console.log(data);
        setSubmitted(true);
        e.target.reset();
        setTimeout(() => {
            setSubmitted(false);
        }, 2000);
    };

    return (
        <>
            <form onSubmit={handleSubmit(onSubmit)}>
                <label>First Name</label>
                <input {...register("FirstNameRequired", { required: true, maxLength: 10 })} placeholder="First Name" />
                {error.FirstNameRequired && <p>First Name is required</p>}
                <label>Last Name</label>
                <input {...register("LastNameRequired", { required: true, maxLength: 10 })} placeholder="Last Name" />
                {error.LastNameRequired && <p>Last Name is required</p>}
                {submitted && <div className="success-message">Form has been submitted</div>}
                <input type="submit" />
            </form>
        </>
    );
}

export default App;
 
CSS Code
 
body {
    background: black;
    font-family: sans-serif;
}

form {
    border: 5px solid #a7a7a7;
    border-radius: 5px;
    padding: 60px 40px;
    max-width: 400px;
    margin: 50px auto;
}

input {
    box-sizing: border-box;
    width: 100%;
    border-radius: 3px;
    padding: 10px 15px;
}

label {
    line-height: 3;
    display: block;
    margin-bottom: 10px;
    margin-top: 20px;
    color: white;
}

button[type="submit"],
input[type="submit"] {
    background: rgb(158, 87, 25);
    color: white;
    text-transform: uppercase;
    border: none;
    cursor: pointer;
    margin-top: 40px;
    padding: 20px;
    letter-spacing: 10px;
}

button[type="submit"],
input[type="submit"]:hover {
    background: rgb(135, 74, 21);
}

.success-message {
    color: rgb(7, 204, 7);
    margin: 10px;
    font-size: 15px;
}


p {
    color: red;
}
 
React Hook Form
 
 
 

2. Formik

 
Formik makes managing forms in React, NextJS, and VueJs easier. It handles form status, validation, and submission, which can be simplified to create user-friendly forms. With Formik, you can create cool forms with less code.

Why should we use Formik?

 
Formik makes managing forms easier by handling form status well. It helps set up validation rules easily. Using this, we can create a form that gives an immediate response so that the user can understand.
 
It fits smoothly with React ecosystem tools like Yup and React Native. Also, Formik has a big community and clear documentation, which makes fixing problems and learning easier.
 
Weekly downloads via npm: 2m - 2.5m
 
npm i formik
 
JSX Code
 
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import './FormComponent.css';

const App = () => {
    const handleSubmit = (data, { resetForm }) => {
        alert('Form submitted successfully');
        resetForm();
        console.log(data);
    };

    const initialValues = { name: '', email: '', password: '', };

    const validate = values => {
        const errors = {};
        if (!values.name) {
            errors.name = 'Name is required';
        }
        if (!values.email) {
            errors.email = 'Email is required';
        } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
            errors.email = 'Invalid email address';
        }
        if (!values.password) {
            errors.password = 'Password is required';
        } else if (values.password.length < 8) {
            errors.password = 'Password must be at least 8 characters';
        }
        return errors;
    };

    return (
        <div className="form-container">
            <h2 className='heading'>Form Validation with Formik</h2>
            <Formik
                initialValues={initialValues}
                validate={validate}
                onSubmit={handleSubmit}
            >
                <Form>
                    <div className="form-group">
                        <label htmlFor="name">Name</label>
                        <Field type="text" name="name" />
                        <ErrorMessage name="name" component="div" className="error" />
                    </div>
                    <div className="form-group">
                        <label htmlFor="email">Email</label>
                        <Field type="email" name="email" />
                        <ErrorMessage name="email" component="div" className="error" />
                    </div>
                    <div className="form-group">
                        <label htmlFor="password">Password</label>
                        <Field type="password" name="password" />
                        <ErrorMessage name="password" component="div" className="error" />
                    </div>
                    <button type="submit">Submit</button>
                </Form>
            </Formik>
        </div>
    );
};

export default App;
 
CSS Code
 
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: cursive;
    color: white;
}

.form-container {
    background-color: rgba(14, 13, 18, 0.933);
    height: 100vh;
}

.heading {
    text-align: center;
    margin-bottom: 20px;
    padding-top: 20px;
}

form {
    border: 5px solid white;
    padding: 50px 30px;
    max-width: 400px;
    margin: 0 auto;
}

.form-group {
    margin-bottom: 20px;
}

input {
    border-radius: 5px;
    width: 100%;
    padding: 8px;
    margin: 5px 0 10px 0;
    font-size: 16px;
    color: black;
}

.error {
    color: red;
}

button {
    padding: 10px 20px;
    margin: 10px 0;
    border-radius: 5px;
    transition: 0.1s all;
    width: 100%;
    letter-spacing: 5px;
    background-color: rgb(177, 94, 108);
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: rgb(163, 84, 97);
}
 
React Formik Hook
 
 

3. Yup Library

 
Yup serves as a JavaScript library specifically designed for schema validation. People often use it with form tools like Formik or React Hook Form to make sure users enter the right kind of information.

Why should we use Yup?

 
Yup Validation: Enjoy robust data validation with Yup, offering sophisticated rule definitions for your data integrity needs.
 
Clear Syntax: With its simple and clear syntax, Yup simplifies the process of setting up validation rules, making it a breeze to define schema validations.
 
Error Messages: Yup allows personalized error messages, ensuring users receive clear and actionable feedback in case of validation errors.
 
Seamless Integration: Integrate Yup effortlessly with popular form libraries like Formik and React Hook Form, enhancing your React app's validation capabilities.
 
Schema Reuse: Save time and maintain consistency by reusing schemas across your application, thanks to Yup's reusable schema feature.
 
Weekly downloads via npm: 4.5m - 4.7m
 
npm i yup
 
JSX Code
 
import React, { useState } from 'react';
import * as yup from 'yup';
import './FormComponent.css'

const schema = yup.object().shape({
    name: yup.string().required('Name is required'),
    email: yup.string().email('Invalid email').required('Email is required'),
    password: yup.string().min(8, 'Password must be at least 8 characters').required('Password is required'),
});

const App = () => {
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        password: ''
    });
    const [errors, setErrors] = useState({});

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({ ...formData, [name]: value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            await schema.validate(formData, { abortEarly: false });
            console.log('Form data:', formData);
            alert('Form has been submitted');
            setFormData({ name: '', email: '', password: '' });
            setErrors({});
        } catch (err) {
            const newErrors = {};
            err.inner.forEach(error => {
                newErrors[error.path] = error.message;
            });
            setErrors(newErrors);
        }
    };

    return (
        <div className='main-container'>
            <div className='heading'>
                <h2>Form Validation with Yup</h2>
            </div>
            <form className='form-group' onSubmit={handleSubmit}>
                <div>
                    <label>Name:</label>
                    <input type="text" name="name" value={formData.name} onChange={handleChange} />
                    {errors.name && <p>{errors.name}</p>}
                </div>
                <div>
                    <label>Email:</label>
                    <input type="text" name="email" value={formData.email} onChange={handleChange} />
                    {errors.email && <p>{errors.email}</p>}
                </div>
                <div>
                    <label>Password:</label>
                    <input type="password" name="password" value={formData.password} onChange={handleChange} />
                    {errors.password && <p>{errors.password}</p>}
                </div>
                <button type="submit">Submit</button>
            </form>
        </div>
    );
};

export default App;
 
CSS Code
 
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: cursive;
    color: white;
}

.main-container {
    background-color: rgba(14, 13, 18, 0.933);
    height: 100vh;
}

.heading {
    text-align: center;
    margin-bottom: 20px;
    padding-top: 20px;
}

form {
    border: 5px solid rgb(156, 155, 155);
    padding: 50px 30px;
    max-width: 400px;
    margin: 0 auto;
}

.form-group {
    margin-bottom: 20px;
}

input {
    border-radius: 5px;
    width: 100%;
    padding: 8px;
    margin: 5px 0 10px 0;
    font-size: 16px;
    color: black;
}

div p {
    color: red;
}

button {
    padding: 10px 20px;
    margin: 10px 0;
    border-radius: 5px;
    transition: 0.1s all;
    width: 100%;
    letter-spacing: 5px;
    background-color: rgb(177, 94, 108);
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: rgb(163, 84, 97);
}
 
React Form with Yup
 
 

4. React Final Form

 
React Final Form is like a buddy in the React community that makes form-building a breeze. It's all about keeping things simple and user-friendly. It gives you the freedom and strength to manage your form status, make sure everything's correct, and send it off when it's ready.


Why should we use React Final Form?

 
React Final Form makes managing forms a breeze, taking away the headache of validation and ensuring everything runs seamlessly, even in larger applications.
 
Weekly downloads via npm: 0.2m - 0.3m
 
npm i react-final-form
 
JSX Code
 
import React from 'react';
import { Form, Field } from 'react-final-form';
import './FormComponent.css'; // Import your CSS file for styling

const initialValues = {
    name: '',
    email: '',
    password: '',
};

const App = () => {
    const handleSubmit = (values, form) => {
        alert('Form submitted successfully');
        form.restart(); // Reset both values and touched states
    };

    const validate = values => {
        const errors = {};
        if (!values.name) {
            errors.name = 'Name cannot be empty';
        }
        if (!values.email) {
            errors.email = 'Email is required';
        } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
            errors.email = 'Invalid email address';
        }
        if (!values.password) {
            errors.password = 'Password is required';
        } else if (values.password.length < 6) {
            errors.password = 'Password must be at least 6 characters';
        }
        return errors;
    };

    return (
        <div className="form-container">
            <h2 className='heading'>Form Validation with Final Form</h2>
            <Form
                initialValues={initialValues}
                onSubmit={handleSubmit}
                validate={validate}
                render={({ handleSubmit }) => (
                    <form onSubmit={handleSubmit}>
                        <div className="form-group">
                            <label htmlFor="name">Name</label>
                            <Field name="name">
                                {({ input, meta }) => (
                                    <div className='error'>
                                        <input {...input} type="text" className={meta.error && meta.touched ? 'error' : ''} />
                                        {meta.error && meta.touched && meta.error}
                                    </div>
                                )}
                            </Field>
                        </div>
                        <div className="form-group">
                            <label htmlFor="email">Email</label>
                            <Field name="email">
                                {({ input, meta }) => (
                                    <div className='error'>
                                        <input {...input} type="email" className={meta.error && meta.touched ? 'error' : ''} />
                                        {meta.error && meta.touched && meta.error}
                                    </div>
                                )}
                            </Field>
                        </div>
                        <div className="form-group">
                            <label htmlFor="password">Password</label>
                            <Field name="password">
                                {({ input, meta }) => (
                                    <div className='error'>
                                        <input {...input} type="password" className={meta.error && meta.touched ? 'error' : ''} />
                                        {meta.error && meta.touched && meta.error}
                                    </div>
                                )}
                            </Field>
                        </div>
                        <button type="submit">Submit</button>
                    </form>
                )}
            />
        </div>
    );
};

export default App;
 
CSS Code
 
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: cursive;
    color: white;
}

.form-container {
    background-color: rgba(14, 13, 18, 0.933);
    height: 100vh;
}

.heading {
    text-align: center;
    margin-bottom: 20px;
    padding-top: 20px;
}

form {
    max-width: 400px;
    margin: 0 auto;
}

.form-group {
    margin-bottom: 20px;
}

input {
    border-radius: 5px;
    width: 100%;
    padding: 8px;
    margin: 5px 0 10px 0;
    font-size: 16px;
    color: black;
}

.error {
    color: red;
}

button {
    padding: 10px 20px;
    margin: 10px 0;
    border-radius: 5px;
    transition: 0.1s all;
    width: 100%;
    letter-spacing: 5px;
    background-color: rgb(177, 94, 108);
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: rgb(163, 84, 97);
}
 
React Final Form
 

 

Which one should I choose?

 
Among the five libraries mentioned (React Hook Form, Formik, Yup, and Final Form), React Hook Form stands out as the most versatile and widely used option for several reasons:
 
Easy to Use: React Hook Form makes managing forms simple. With less code, we can create complex forms so that we can easily understand the code.
 
Fast Performance: It works fast, even with big forms. So, your app won't slow down.
 
Works Well with React: The React Hook Form fits right in with React. You can add it to your app without any fuss.

Lots of People Use It: Many React developers like using the React Hook Form. If you need help, there are plenty of others who know how to use it.

Gets Regular Updates: It's always getting better. The people who make React Hook Form are always fixing bugs and adding new stuff.

Flexible: You can customize it to fit your needs. So, you're not stuck with a one-size-fits-all solution.

Lots of Help Available: The React Hook Form comes with lots of guides and examples. If you get stuck, you can find help easily.
 
While React Hook Form is a popular choice for form validation in React applications due to its simplicity, ease of use, and robust feature set, the best library to choose depends on the specific requirements of your project and your preferences as a developer.
 
Each of the mentioned libraries has its own strengths and use cases:
 
Yup: It focuses primarily on schema-based validation and is often used in conjunction with other form libraries like Formik or React Hook Form.
 
Formik: This is good for beginners, as there are many examples online that will help in understanding it. This library is becoming popular in today's time.
 
Final Form: Manage even the trickiest forms easily with this tool. No matter how big or complex your forms become, it keeps things running smoothly.
 
It is important to keep in mind that while selecting any one of these four libraries, you should first know the needs and priorities of your project and then make the decision.
 
 

Conclusion

 
While Formik stands out as a recommended choice among the top form validation libraries for React, each library Yup, React Hook Form, and Final Form offers unique features and benefits. Therefore, explore your options thoroughly to select the library that best aligns with your project requirements and preferences.
 
If you're looking to do form validation without using any external libraries, check out this article: How To Validate Form in React: Step-by-Step Guide.
 
If you have any questions regarding this article or any other web development, then you can ask them in the question box given below, and you will get the answer as soon as possible.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Diya Jain ( diya )

The Dev without a Degree

Joined On 10 Apr 2024

More from Diya Jain

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....

Top Strategies for Search Bar Optimization on Major Platforms

web-development

6 Sep 2024

Discover top strategies for search bar optimization on major platforms. Enhance real-time ....

Top Strategies to Optimize ReactJS Application Performance for Faster Load Times

react-js

23 Aug 2024

From this article, you will discover the best practices to enhance the speed of loading yo....

Comprehensive Guide to Tooltips in ReactJS

react-js

5 Jun 2024

Explore ReactJS tooltips from start to finish! Learn how to add, customize, troubleshoot, ....

Comprehensive Guide to React Hooks: When and How to Use Each Hook Effectively

react-js

9 Jul 2024

In React, we use a component-based structure. A component is like a building block of code....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....