React 17-Form Validation Tutorial With Example

React 17 Tutorial- Form Validation Tutorial

Friends, in this tutorial, we will learn to build a basic form from scratch in a React application. We will be doing so using Bootstrap 4 and this form would allow registering a user. It will have the fields a name, email, password.

We will get to see the following steps in this guide:

  • Getting Started
  • Create Component In React
  • Create React Form With Bootstrap 4
  • Form Validation And Handling Form Data In React
  • Conclusion

 

React Form Validation Tutorial With Example

Step 1- Getting Started

The very first step is just to install the new React app:

npx create-react-app react-form-validation

Then, we will get inside the project directory:

cd react-form-validation

 

Afterward, we will install the Bootstrap 4 UI framework and it offers many UI components. We have to create the user form using the Bootstrap 4 in React:

npm install bootstrap --save

 

Further is required to 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;

 

Step 2- Create Component In React

The next step is to create a component in React. So, we create a component folder inside the src folder and then, create user-form.component.js file. Then, we have to paste the given code into it:

import React, { Component } from "react";

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

 

Further, we will 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;

 

Step 3- Create React Form With Bootstrap 4

Here, in this step, we have to create a basic user form in Recat with the help of Bootstrap4. We will add name, email and password form elements inside the React’s UserForm component.

 

Then, we will add the given code in the 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>
        );
    }
}

 

Step 4- Form Validation And Handling Form Data In React

Since, we know that forms are a significant part of the modern web and mobile apps. These forms allow the software and human interaction in a straightforward manner. So, in this step, we will see how to validate a basic form and handle the form data in React.

 

Further, we have to add the following code in the src/component/user-form.component.js file.

To validate the email field, we declare the regEx 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][email protected][a-zA-Z0-9]+\.[A-Za-z]+$/
)

 

Afterward, we will use the formValid object, and this object checks 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 have defined the name, email, password in React state along with isError object. This isError object will hold the form errors for every data:

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>
        );
    }
}

 

Here, with the help of onChange={this.formValChange} event. We are using the JavaScript switch statement and checking whether 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 show the error messages in React component.

 

Conclusion

We have reached the end of this tutorial in which we have learnt to validate client-side validation with minimum characters, email validation with the regular expression and password validation in React.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *