React 16+ Form Validation Tutorial with Example

By Digamber Rawat Last updated on
This is a React form validation step by step tutorial. In this tutorial, we will learn to build a basic form from scratch in React. You can check out the complete form validation tutorial code on Github.

We will create a basic React app, in which we will create a basic user registration form using Bootstrap 4. This React form will allow us to register a user. It will have following form fields such as name, email, and password.

Getting Started

We will install React app using create-react-app.

npx create-react-app react-form-validation

Get inside the project directory.

cd react-form-validation

Install Bootstrap 4 UI framework, and it offers many UI components. We will create user form using Bootstrap 4 in React.

npm install bootstrap --save

Next, import bootstrap.min.css from node_modules in src/App.js file.

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

function App() {
  return (
    <div className="App">
      <h3>React Form Validation Tutorial</h3>
    </div>
  );
}

export default App;

Create Component in React

Create a component in React, create component folder inside the src folder then create user-form.component.js file. Next, paste the following code in here.

import React, { Component } from "react";

export default class UserForm extends Component {
    render() {
        return (
            <div>
                <h3>React Form Component</h3>
            </div>
        );
    }
}

Next, import the UserForm component in src/App.js file.

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import UserForm from './component/user-form.component';


function App() {
  return (
    <div className="container">
      <UserForm />
    </div>
  );
}

export default App;

Create React Form with Bootstrap 4

Next, create a basic user form in React with the help of Bootstrap 4. We will add name, email, and password form elements inside the React’s UserForm component.

Add the code component/user-form.component.js file.

import React, { Component } from "react";

export default class UserForm extends Component {
    render() {
        return (
            <form>
                <div className="form-group">
                    <label>Name</label>
                    <input type="text" className="form-control" />
                    <small className="text-danger">Name is required.</small>
                </div>

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

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

                <button type="submit" className="btn btn-block btn-danger">Create User</button>
            </form>
        );
    }
}

Form Validation and Handling Form Data in React

Forms are an essential part of any modern web and mobile applications, and forms allow software and human interaction in a straightforward way. In this step, we will validate a basic form and handle the form data in React.

Add the following code in src/component/user-form.component.js file.

To validate the email field, declare the regExp instance outside the React component using the RegExp object and pass the regular expression in the RegExp object.

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

Next, we are using the formValid object, and this object is checking whether the form state is valid or not based on the isError object.

const formValid = ({ isError, ...rest }) => {
    let isValid = false;

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

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

    return isValid;
};

We defined the name, email, password in React state along with isError object. This isError object will hold the form errors for every state.

export default class UserForm extends Component {
    constructor(props) {
        super(props)

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


    onSubmit = e => {
        e.preventDefault();

        if (formValid(this.state)) {
            console.log(this.state)
        } else {
            console.log("Form is invalid!");
        }
    };


    formValChange = e => {
        e.preventDefault();
        const { name, value } = e.target;
        let isError = { ...this.state.isError };

        switch (name) {
            case "name":
                isError.name =
                    value.length < 4 ? "Atleast 4 characaters required" : "";
                break;
            case "email":
                isError.email = regExp.test(value)
                    ? ""
                    : "Email address is invalid";
                break;
            case "password":
                isError.password =
                    value.length < 6 ? "Atleast 6 characaters required" : "";
                break;
            default:
                break;
        }

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

    render() {
        const { isError } = this.state;

        return (
            <form onSubmit={this.onSubmit} noValidate>
                <div className="form-group">
                    <label>Name</label>
                    <input
                        type="text"
                        className={isError.name.length > 0 ? "is-invalid form-control" : "form-control"}
                        name="name"
                        onChange={this.formValChange}
                    />
                    {isError.name.length > 0 && (
                        <span className="invalid-feedback">{isError.name}</span>
                    )}
                </div>

                <div className="form-group">
                    <label>Email</label>
                    <input
                        type="email"
                        className={isError.email.length > 0 ? "is-invalid form-control" : "form-control"}
                        name="email"
                        onChange={this.formValChange}
                    />
                    {isError.email.length > 0 && (
                        <span className="invalid-feedback">{isError.email}</span>
                    )}
                </div>

                <div className="form-group">
                    <label>Password</label>
                    <input
                        type="password"
                        className={isError.password.length > 0 ? "is-invalid form-control" : "form-control"}
                        name="password"
                        onChange={this.formValChange}
                    />
                    {isError.password.length > 0 && (
                        <span className="invalid-feedback">{isError.password}</span>
                    )}
                </div>

                <button type="submit" className="btn btn-block btn-danger">Create User</button>
            </form>
        );
    }
}

Next, with the help of onChange={this.formValChange} event. We are using the JavaScript switch statement and checking whether the our form state matches the specific condition and returning the error messages. When the state doesn’t match up with a specific condition. This way we are showing the error messages in React component.

react 16+ form validation

Conclusion

Finally, our React 16+ form validation tutorial with example is over. This is just a basic form validation approach to React. We have learned to validate client-side validation with minimum characters, email validation with the regular expression and password validation in React. I hope you will like this tutorial, please consider it sharing with others.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.