Add Form Validation In ReactJS

Introduction

 
In this article we will learn basic React form validations. Form validation is an important part of web application development. Forms are used in Web applications to save user inputs.Validation is used to check that the values in form input fields match to particular expectations.
 
Prerequisites
  • We should have a basic knowledge of ReactJS
  • Visual Studio Code IDE should be installed on your system

Create a ReactJS Project

  1. npx create-reatc-app formvalidation  
Now open the newly created project in Visual Studio Code and install Reactstrap and Bootstrap by using the following commands.<
  1. npm install --save bootstrap    
  2. npm install --save reactstrap react react-dom  
  1. import 'bootstrap/dist/css/bootstrap.min.css';    
Now, go to the "src" folder and add a new component named 'EmployeeForm.js'
 

Now, open the EmployeForm.js file and add the following code:

  1. import React from 'react';  
  2. import './App.css'  
  3. import { Button, Card, CardFooter, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
  4.   
  5. class EmployeeForm extends React.Component {  
  6.     constructor() {  
  7.       super();  
  8.       this.state = {  
  9.         entities: {},  
  10.         errors: {}  
  11.       }  
  12.       this.handleChange = this.handleChange.bind(this);  
  13.       this.EmployeeForm = this.EmployeeForm.bind(this);  
  14.     };  
  15.        
  16.     handleChange(e) {  
  17.       let entities = this.state.entities;  
  18.       entities[e.target.name] = e.target.value;  
  19.       this.setState({  
  20.         entities  
  21.       });  
  22.   
  23.     }  
  24.   
  25.     EmployeeForm(e) {  
  26.       e.preventDefault();  
  27.       if (this.validateemployee()) {  
  28.           let entities = {};  
  29.           entities["EmployeeName"] = "";  
  30.           entities["Email"] = "";  
  31.           entities["City"] = "";  
  32.           entities["Password"] = ""
  33.           entities["Department"] = "";
  34.           this.setState({entities:entities});  
  35.           alert("Employee Details Save Successully");  
  36.       }  
  37.     }  
  38.     validateemployee() {  
  39.       let entities = this.state.entities;  
  40.       let errors = {};  
  41.       let IsValid = true;  
  42.   
  43.       if (!entities["EmployeeName"]) {  
  44.         IsValid = false;  
  45.         errors["EmployeeName"] = "Employee name is Required";  
  46.       }  
  47.         
  48.       if (!entities["Email"]) {  
  49.         IsValid = false;  
  50.         errors["Email"] = "Email is Required";  
  51.       }  
  52.   
  53.       if (typeof entities["Email"] !== "#ff0000") {  
  54.         var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);  
  55.         if (!pattern.test(entities["Email"])) {  
  56.           IsValid = false;  
  57.           errors["Email"] = "Email is not Valid";  
  58.         }  
  59.       }  
  60.       if (!entities["City"]) {  
  61.         IsValid = false;  
  62.         errors["City"] = "City is Required";  
  63.       }  
  64.       if (!entities["Department"]) {  
  65.         IsValid = false;  
  66.         errors["Department"] = "Department is Required";  
  67.       }  
  68.       if (!entities["Password"]) {  
  69.         IsValid = false;  
  70.         errors["Password"] = "Password is Required";  
  71.       }  
  72.       this.setState({  
  73.         errors: errors  
  74.       });  
  75.       return IsValid;  
  76.     }  
  77.   render() {  
  78.     return (  
  79.         <div className="app flex-row align-items-center">  
  80.         <Container>  
  81.           <Row className="justify-content-center">  
  82.             <Col md="9" lg="7" xl="6">  
  83.               <Card className="mx-4">  
  84.                 <CardBody className="p-4">  
  85.                   <Form  method="post"  name="EmpForm"  onSubmit= {this.EmployeeForm}>  
  86.                     <div class="row" className="mb-2 pageheading">  
  87.                       <div class="col-sm-12 btn btn-primary">  
  88.                         Sign Up  
  89.                         </div>  
  90.                     </div>  
  91.                     <Input type="text" className="mrgn" name="EmployeeName" value={this.state.entities.EmployeeName} onChange={this.handleChange}  placeholder="Enter Email" />  
  92.                       <div className="errorMsg">{this.state.errors.EmployeeName}</div>  
  93.                       <Input type="text" className="mrgn" name="Email" value={this.state.entities.Email} onChange={this.handleChange}  placeholder="Enter Email" />  
  94.                       <div className="errorMsg">{this.state.errors.Email}</div>  
  95.                       <Input type="password"  className="mrgn" name="Password" value={this.state.entities.Password} onChange={this.handleChange} placeholder="Enter Password" />  
  96.                       <div className="errorMsg">{this.state.errors.Password}</div>  
  97.                       <Input type="text"  className="mrgn" name="City" value={this.state.entities.City} onChange={this.handleChange} placeholder="Enter City" />  
  98.                       <div className="errorMsg">{this.state.errors.City}</div>  
  99.                       <Input type="text"  className="mrgn" name="Department" value={this.state.entities.Department} onChange={this.handleChange} placeholder="Enter Department" />  
  100.                       <div className="errorMsg">{this.state.errors.Department}</div>  
  101.                      <Button type="submit" color="success" block  >Register</Button>  
  102.                   </Form>  
  103.                 </CardBody>  
  104.               </Card>  
  105.             </Col>  
  106.           </Row>  
  107.         </Container>  
  108.       </div>  
  109.       );  
  110.   }  
  111. }  
  112. export default EmployeeForm;  
Now open App.js file and add the following code:
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import EmployeeForm from './Employeeform';  
  5.   
  6. function App() {  
  7.   return (  
  8.     <div className="App">  
  9.      <EmployeeForm></EmployeeForm>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. export default App; 
 
Now run the project and check result, without entering any value in textboxes click on button, it's showing a validation message.
 
 
 
Now enter some values in textboxes and click on Register button 
 
 
It shows that the  email is not valid, so now enter a proper mail id and check
 
 
 

Summary

 
In this article, we learned about simple form validations in ReactJS Applications.