How to Create Forms and Add Validation in React Js

React form validation tutorial; This step-by-step tutorial aims to teach pragmatic solution regarding how to create forms in react, access form input fields values, validate the input field and submit forms.

A web developer knows what role form element plays in collecting information from the users; HTML offers tons of elements that help build web application.

Similarly, the HTML form provides input text, radio buttons, checkboxes, select dropdown elements. These elements allow you to build a form that helps acquire the information from the site users, but it is a tedious job to work with forms; web developers know what exactly it takes to work with forms.

In this react form validation guide, I will demonstrate how to build a dynamic form that collects information from the user simultaneously; we will show you how to access the form input values easily and validate the form in react application.

React Js Bootstrap Form Validation Example

  • Step 1: Install React Project
  • Step 2: Set Up Bootstrap in React
  • Step 3: Create Reusable Form Component
  • Step 4: Build Form using Bootstrap Pacakage
  • Step 5: Add Form Validation in React Form
  • Step 6: Start React Application

Install React Project

In the first segment, we will establish the development environment, Create React App solves our problem, which helps to install React app.

npx create-react-app react-blog-app

Besides, move inside the app folder.

cd react-blog-app

Set Up Bootstrap in React

This step guides installing the Bootstrap package into the React app; this library produces beautiful UI components in less time. But, first, let us execute the recommended command to install this quintessential UI library in react.

npm i bootstrap

To take full advantage of profound bootstrap, add the Bootstrap CSS in the react component; we need to import the CSS path in the main App.js file recklessly.

import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

function App() {
  return (
    <div className="ReactFormApp">
       {/* .... */}
    </div>
  );
}

export default App;

Create Reusable Form Component

Creating a reusable component is always a good idea; it has various benefits; notwithstanding; the most important benefit is the ease of managing the code and using the component anywhere or anytime.

In this step, we will create a separate form component and register it into the main App.js file for handling the form validation profoundly.

Its better to create a directory by the name of the ‘components’; after that, create a new file ‘form.component.js’ and then place the given code in the components/form.component.js file.

import React, { Component } from "react";

export default class Form extends Component {
    render() {
        return (
            <div className="container">
                {/* ... */}
            </div>
        );
    }
}

The reusable form component has been created; now, we need to register this component in the src/App.js file.


import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import Form from '../src/components/form.component';


function App() {
  return (
    <div className="ReactFormApp">
      <Form />
    </div>
  );
}

export default App;

Build Form using Bootstrap Pacakage

This segment will show you how to create a simple form in React app using the Bootstrap library. Bootstrap offers a form control component that makes the form building exorbitantly facile; thus, we will use the Bootstrap component to build the form swiftly.

Update code in components/form.component.js file:

import React, { Component } from "react";

export default class Form extends Component {
    render() {
        return (
            <div className="container">
                <div className="card mt-5">
                    <form className="card-body">
                        <div className="form-group mb-3">
                            <label className="mb-2"><strong>Name</strong></label>
                            <input type="text" className="form-control" />
                            <small className="text-danger">Error section</small>
                        </div>

                        <div className="form-group mb-3">
                            <label className="mb-2"><strong>Email</strong></label>
                            <input type="email" className="form-control" />
                        </div>

                        <div className="form-group mb-3">
                            <label className="mb-2"><strong>Password</strong></label>
                            <input type="text" className="form-control" />
                        </div>

                        <div className="d-grid mt-3">
                            <button type="submit" className="btn btn-block btn-primary">Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        );
    }
}

Add Form Validation in React Form

Let’s start implementing validation in form fields; basically, we have three input fields which are as follows the name, email and password. In the name field, we have added the minimum character validation and added the HTML 5 built-in validation to make the required validation.

In the email field, we added the regular expression validation, lastly added the password validation with required and minimum character validation.

Update components/form.component.js file:

import React, { Component } from "react";

const regularExpression = RegExp(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/)

const validation = ({ error, ...rest }) => {
    let checkValidation = false;

    Object.values(error).forEach(val => {
        if (val.length > 0) {
            checkValidation = false
        } else {
            checkValidation = true
        }
    });

    Object.values(rest).forEach(val => {
        if (val === null) {
            checkValidation = false
        } else {
            checkValidation = true
        }
    });

    return checkValidation;
};

export default class Form extends Component {

    constructor(props) {
        super(props)

        this.state = {
            name: '',
            email: '',
            password: '',
            error: {
                name: '',
                email: '',
                password: ''
            }
        }
    }

    onFormSubmit = event => {
        event.preventDefault();

        if (validation(this.state)) {
            console.log(this.state)
        } else {
            console.log("Error occured");
        }
    };


    formObject = event => {

        event.preventDefault();

        const { name, value } = event.target;
        let error = { ...this.state.error };

        switch (name) {
            case "name":
                error.name = value.length < 5 ? "Name should be 5 characaters long" : "";
                break;
            case "email":
                error.email = regularExpression.test(value)
                    ? ""
                    : "Email is not valid";
                break;
            case "password":
                error.password =
                    value.length < 5 ? "Password should 5 characaters long" : "";
                break;
            default:
                break;
        }

        this.setState({
            error,
            [name]: value
        })
    };

    render() {

        const { error } = this.state;

        return (
            <div className="container">
                <div className="card mt-5">
                    <form className="card-body" onSubmit={this.onFormSubmit}>
                       
                        <div className="form-group mb-3">
                            <label className="mb-2"><strong>Name</strong></label>
                            <input 
                               required
                               type="text" 
                               name="name"
                               onChange={this.formObject}
                               className={error.name.length > 0 ? "is-invalid form-control" : "form-control"}/>
                            
                                {error.name.length > 0 && (
                                <span className="invalid-feedback">{error.name}</span>
                                )}
                        </div>

                        <div className="form-group mb-3">
                            <label className="mb-2"><strong>Email</strong></label>
                            <input
                                required
                                type="email"
                                name="email"
                                className={error.email.length > 0 ? "is-invalid form-control" : "form-control"}
                                onChange={this.formObject}/>

                                {error.email.length > 0 && (
                                    <span className="invalid-feedback">{error.email}</span>
                                )}
                        </div>

                        <div className="form-group mb-3">
                            <label className="mb-2"><strong>Password</strong></label>
                            <input
                                required
                                type="password"
                                name="password"
                                className={error.password.length > 0 ? "is-invalid form-control" : "form-control"}
                                onChange={this.formObject}/>

                                {error.password.length > 0 && (
                                    <span className="invalid-feedback">{error.password}</span>
                                )}
                        </div>

                        <div className="d-grid mt-3">
                            <button type="submit" className="btn btn-block btn-primary">Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        );
    }
}

Start React Application

We have almost reached the final part of this informative guide, now you need to start an app development server. Head over to the command prompt and make sure to evoke the following command.

npm start

Here is the url which you can use to view the app on the browser.

http://localhost:3000

React form validaiton

Conclusion

The React form validation tutorial has been completed; this example intended to enlighten on the most common functionality of every application that was building and validating the form.

The audacity of this tutorial followed a pragmatic approach, which managed to help us comprehend how to create form using bootstrap in react similarly how to implement form validation in react app on form submission.