How to use Custom Form Validation In React

React custom form validation example; In this tutorial, i will show you complete guide from scratch on how to integrate custom validation rules with forms in react js apps.

Form validation in React allows an error message to be displayed if the user has not correctly filled out the form with the expected type of input. There are several ways to validate forms in React; however, this shot will focus on creating a validator function with validation rules.

Now in this Custom Form Validation and Handling Form Data in React tutorial; i will create a form and integrate custom validation rules with forms in react js app with the bootstrap 4 library.

React Custom Form Validation Example

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

Step 1 – Create React App

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

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

Create CustomForm.js file. So, visit the src directory of your react js app and create a custom form validation component file named CustomForm.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 CustomForm 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 - Laratutorials.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 CustomForm;

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

Step 4 – Import Custom Form Component in App.js

Import CustomForm.js file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import CustomForm from './CustomForm'
function App() {  
    
  return (  
    <div className="App">  
      <CustomForm />  
    </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

Leave a Comment