In our previous React tutorial, we have explained file upload in React. In this tutorial, we will explain how to create form with validation in React.
HTML Form is an important part of web applications with inputs to allows to enter data to process at server end.
If you’re working with React and wants to create forms with validation then it’s very simple. You can easily create HTML Form with validation using React.
We will cover this tutorial step by step to create React application with required module installation to create form and implement client side validation with React.
Also, read:
- Simple React File Upload with Node.js
- Best PDF Viewer Component for React
- How to Map Components in React
- How to Make API Call in React
So let’s get started with the tutorial to create form and implement client side validation in React application. Before proceeding, make sure you have Node and NPM installed on your computer.
Step1: Create React Application
First we will create React application react-form-validation-demo
to create form and implement validation using following command.
npx create-react-app react-form-validation-demo
We will go the react project react-form-validation-demo
cd react-form-validation-demo
Now we will install React Bootstrap using folowing command:
npm install bootstrap
We will make changes in src/index.js
to add below line to include Bootstrap CSS to create form with Bootstrap.
import 'bootstrap/dist/css/bootstrap.css';
Step2: Create Form Component
We will create form component src/Form.js
file and create form with email and password and submit button.
import React, { Component } from 'react'; import { FormValidation } from './FormValidation'; import './Form.css'; class Form extends Component { render () { return ( <form className="signupForm"> <br/> <h2>React Form with Validation</h2> <br/> <h5>Sign up Form</h5> <div className="panel panel-default"> <FormValidation FormValidation={this.state.FormValidation} /> </div> <div className={`form-group ${this.errorClass(this.state.FormValidation.email)}`}> <label htmlFor="email">Email</label> <input type="email" required className="form-control" name="email" placeholder="Email" value={this.state.email} onChange={this.validateUserInput} /> </div> <div className={`form-group ${this.errorClass(this.state.FormValidation.password)}`}> <label htmlFor="password">Password</label> <input type="password" className="form-control" name="password" placeholder="Password" value={this.state.password} onChange={this.validateUserInput} /> </div> <button type="submit" className="btn btn-primary" disabled={!this.state.validateForm}>Sign up</button> </form> ) } } export default Form;
Step3: Import Form Component
In src/App.js
file, we will import Form
component to handle Form creation.
import React, { Component } from 'react'; import './App.css'; import Form from './Form.js'; class App extends Component { render() { return ( <div className="App"> <Form /> </div> ); } }export default App;
Step4: Create Form Validation Error Display Component
We will also create a component js/FormValidation.js
file to handle Form validation error message display.
import React from 'react'; export const FormValidation = ({FormValidation}) => <div className='FormValidation'> {Object.keys(FormValidation).map((fieldName, i) => { if(FormValidation[fieldName].length > 0){ return ( <p class="alert alert-danger" key={i}>{fieldName} {FormValidation[fieldName]}</p> ) } else { return ''; } })} </div>
Step5: Implement Form Validation
Now we will make changes into form component src/Form.js
and implement form input validation.
constructor (props) { super(props); this.state = { email: '', password: '', FormValidation: {email: '', password: ''}, validateEmail: false, validatePassword: false, validateForm: false } } validateUserInput = (e) => { const name = e.target.name; const value = e.target.value; this.setState({[name]: value}, () => { this.validateInputField(name, value) }); } validateInputField(inputField, value) { let inputFieldErrors = this.state.FormValidation; let validateEmail = this.state.validateEmail; let validatePassword = this.state.validatePassword; switch(inputField) { case 'email': validateEmail = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i); inputFieldErrors.email = validateEmail ? '' : ' is invalid!'; break; case 'password': validatePassword = value.length >= 6; inputFieldErrors.password = validatePassword ? '': ' is too short!'; break; default: break; } this.setState({FormValidation: inputFieldErrors, validateEmail: validateEmail, validatePassword: validatePassword }, this.validateForms); } validateForms() { this.setState({validateForm: this.state.validateEmail && this.state.validatePassword}); } errorClass(error) { return(error.length === 0 ? '' : 'has-error'); }
Step6: Run React Application
Now we will run our React form validation application using following command.
npm start
We will see the React application form page into browser http://localhost:3000.
You may also like:
- Follow and Unfollow System with PHP & MySQL
- GST Billing System with PHP & MySQL
- Restaurant Management System with PHP & MySQL
- Visitor Management System with PHP & MySQL
- Student Attendance System with PHP & MySQL
- Like and Dislike System with Ajax, PHP & MySQL
- Build Star Rating System with jQuery, PHP & MySQL
- User Registration and Login System with PHP & MySQL
- Build Contact Form with PHP and Ajax
- To-do List Application with Ajax, PHP & MySQL
- Build Event Calendar with jQuery , PHP & MySQL
You can can download the complete source from the Download link below.