React js Custom Form Validation Tutorial Example

React js Custom Form Validation Tutorial Example

React custom form validation example; In this tutorial, you will learn how to add custom validation rules with forms in react js apps.

If you want to add form validation on submitting with a form component in react js app. So this tutorial will create a simple form and add custom validation rules to the forms field on submitting in react app.

Now in this Custom Form Validation and Handling Form Data in React tutorial will provide you step by step guide on how to add custom validation with forms in react js app with the bootstrap 4 library.

How to Add Validation on Custom Form in React JS App

Let’s use the following steps to implement custom form validation in react js app:

  • Step 1 – Create React App
  • Step 2 – Install React Bootstrap
  • Step 3 – Create Custom Form Component with Validation
  • Step 4 – Add Custom Form Component in App.js

Step 1 – Create React App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install React Bootstrap

In this step, execute the following command to install react boostrap library into your react app:

npm install bootstrap --save

npm install react-bootstrap bootstrap

Add bootstrap.min.css file in src/App.js file:

import React, { Component } from 'react'

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

function App() {
  return (
    <div>
      <h2>How to Add Custom Validatin with Forms in React</h2>
    </div>
  );
}

export default App;

Step 3 – Create Custom Form Component with Validation

In this step, create CustomFormValidation.js file. So, visit the src directory of your react js app and create a custom form validation component file named CustomFormValidation.js. And add the following code into it:

import React from 'react'

const defaultState = {
    name:null,
    email:null,
    password:null,
    nameError:null,
    emailError:null,
    passwordError:null
}

class CustomFormValidation extends React.Component{

    constructor(){
        super();
        this.state = defaultState;

        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange(event) {
        const target = event.target;
        var value = target.value;
        const name = target.name;
        
        this.setState({
            [name]: value
        });
        
    }

    validate(){
        let nameError = "";
        let emailError = "";
        let passwordError = "";

        if(!this.state.name){
            nameError = "Name field is required";
        }

        const reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if(!this.state.email || reg.test(this.state.email) === false){
            emailError = "Email Field is Invalid ";
        }

        if(!this.state.password){
            passwordError = "Password field is required";
        }

        if(emailError || nameError || passwordError){
            this.setState({nameError,emailError,passwordError});
            return false;
        }

        return true;
    }

    submit(){
        if(this.validate()){
            console.warn(this.state);
            this.setState(defaultState);
        }
    }

    render(){
        return(
            <div>
                <div className="row">
                    <div className="col-md-6 offset-md-3">
                        
                        <h3>React Custom Form Validation Example - Tutsmake.com</h3><br />
                        
                            <div className="form-row">
                                <div className="form-group col-md-6">
                                    <label>Name :</label>
                                    <input type="text" className="form-control" name="name" value={this.state.name} onChange={this.handleInputChange} />
                                    <span className="text-danger">{this.state.nameError}</span>
                                </div>
                            </div>

                            <div className="form-row">
                                <div className="form-group col-md-6">
                                    <label>Email :</label>
                                    <input type="email" className="form-control" name="email" value={this.state.email} onChange={this.handleInputChange} />
                                    <span className="text-danger">{this.state.emailError}</span>
                                </div>
                            </div>

                            <div className="form-row">
                                <div className="form-group col-md-6">
                                    <label>Password :</label>
                                    <input type="password" className="form-control" name="password" value={this.state.password} onChange={this.handleInputChange} />
                                    <span className="text-danger">{this.state.passwordError}</span>
                                </div>
                            </div>

                            <div className="form-row">
                                <div className="col-md-12 text-center">
                                    <button type="submit" className="btn btn-primary" onClick={()=>this.submit()}>Submit</button>
                                </div>
                            </div>
                        
                    </div>
                </div>
            </div>
        )  
    }
}

export default CustomFormValidation;

Note that, The validate() function check all field validation.

Step 4 – Add Custom Form Component in App.js

In this step, you need to add CustomFormValidation.js file in src/App.js file:

import React from 'react';

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

import CustomFormValidation from './CustomFormValidation'

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

export default App;

Conclusion

React custom form validation example; In this tutorial, you have learned how to add custom validation rules on the forms field on submitting forms in react js apps.

Recommended React JS Posts

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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