In this article we are going to learn about how to implement form validation in ReactJS with simple example.
Description
ReactJS is front-end JavaScript library used for building user interface. It is currently the most famous JavaScript library. It is maintained by
Facebook and a community of individual developers and companies.
Prerequisites
Run following command to create a sample project
- npm install -g create-react-app
- create-react-app reactjs-validation
- cd reactjs-validation
- npm start -o
Once the above command runs successfully, you will find an output on the browser like the below screen.
Note :- Screen output for you might be slightly different as per your version of reactjs.
- Run the below commands for open project in the Visual Studio Code
- Press control + c command, it will ask you a "Terminate batch job (Y/N)?", Press Y to stop the execution
- Write “code .” in your project directory and press enter
The above command will open your created project in the Visual Studio Code like below.
ReactJS form validation
What is validation? - It is the process of checking/ensuring if the provided data by end user is correct or not. If it is not correct or if it's invalid data then we will restrict it and show the appropriate error messages as per field/requirement so that the user will behave to provide the correct/valid data.
In our case, we are going to apply this validation to HTML form using ReactJS.
Example
In this example, we are going to create a Student Admission Form. In this form, we will add Student Name, Email Id, Birth Date, Gender, Phone Number fields to enter data by user. The Screen will look like below.
Let’s start
- Create two new js files into src folder
- AdmissionForm.js
- AdmissionForm.css
- Add following style into AdmissionForm.css
- .formDiv {
- padding: 21px;
- border-radius: 5px;
- background-color: #f2f2f2;
- }
-
- input[type=text], select
- {
- width: 100%;
- padding: 12px 20px;
- margin: 8px 0;
- display: inline-block;
- border: 1px solid #ccc;
- border-radius: 4px;
- box-sizing: border-box;
- }
-
- input[type=submit] {
- width: 100%;
- background-color: #4CAF50;
- color: white;
- padding: 14px 20px;
- margin: 8px 0;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- }
-
- input[type=submit]:hover {
- background-color: #45a049;
- }
- .showError{
- border-color: #a94442 !important;
- color: #a94442 !important;
- margin-bottom: 15px;
- }
- Create a component with name AdmissionForm in AdmissionForm.js and add below code into it
- import React, { Component } from "react";
-
- class AdmissionForm extends Component {
- render() {
- return (
- <h1>This Admission Form Component</h1>
- )
- }
- }
-
- export default AdmissionForm;
- Create a component with name AdmissionForm in AdmissionForm.js and Import AdmissionForm.css file into it.
In this example, I am going to use
- onChange function for binding the input textbox value to state.
- className with ternary operator to apply class base on condition.
- onSubmit callback function to submit the form data.
- handleFormValidation user defined function to validate input fields.
Code
- import React, { Component } from "react";
- import './AdmissionForm.css'
-
- class AdmissionForm extends Component {
- constructor(props) {
- super(props);
- this.state = {
- studName: '',
- emailId: '',
- dob: '',
- gender: 'select',
- phoneNumber: '',
- city: 'select',
- formErrors: {}
- };
-
- this.initialState = this.state;
- }
-
- handleFormValidation() {
- const { studName, emailId, dob, gender, phoneNumber, city } = this.state;
- let formErrors = {};
- let formIsValid = true;
-
-
- if (!studName) {
- formIsValid = false;
- formErrors["studNameErr"] = "Name is required.";
- }
-
-
- if (!emailId) {
- formIsValid = false;
- formErrors["emailIdErr"] = "Email id is required.";
- }
- else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailId))) {
-
- formIsValid = false;
- formErrors["emailIdErr"] = "Invalid email id.";
- }
-
-
- if (!dob) {
- formIsValid = false;
- formErrors["dobErr"] = "Date of birth is required.";
- }
- else {
- var pattern = /^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})$/;
- if (!pattern.test(dob)) {
- formIsValid = false;
- formErrors["dobErr"] = "Invalid date of birth";
- }
- }
-
-
- if (gender === '' || gender === "select") {
- formIsValid = false;
- formErrors["genderErr"] = "Select gender.";
- }
-
-
- if (!phoneNumber) {
- formIsValid = false;
- formErrors["phoneNumberErr"] = "Phone number is required.";
- }
- else {
- var mobPattern = /^(?:(?:\\+|0{0,2})91(\s*[\\-]\s*)?|[0]?)?[789]\d{9}$/;
- if (!mobPattern.test(phoneNumber)) {
- formIsValid = false;
- formErrors["phoneNumberErr"] = "Invalid phone number.";
- }
- }
-
-
- if (city === '' || city === "select") {
- formIsValid = false;
- formErrors["cityErr"] = "Select city.";
- }
-
- this.setState({ formErrors: formErrors });
- return formIsValid;
- }
-
- handleChange = (e) => {
- const { name, value } = e.target;
- this.setState({ [name]: value });
- }
-
- handleSubmit = (e) => {
- e.preventDefault();
-
- if (this.handleFormValidation()) {
- alert('You have been successfully registered.')
- this.setState(this.initialState)
- }
- }
-
- render() {
-
- const { studNameErr, emailIdErr, dobErr, genderErr, phoneNumberErr, cityErr } = this.state.formErrors;
-
- return (
- <div className="formDiv">
- <h3 style={{ textAlign: "center" }} >Student Admission Form </ h3>
- <div>
- <form onSubmit={this.handleSubmit}>
- <div>
- <label htmlFor="studName">Name</label>
- <input type="text" name="studName"
- value={this.state.studName}
- onChange={this.handleChange}
- placeholder="Your name.."
- className={studNameErr ? ' showError' : ''} />
- {studNameErr &&
- <div style={{ color: "red", paddingBottom: 10 }}>{studNameErr}</div>
- }
-
- </div>
- <div>
- <label htmlFor="emailId">Email Id</label>
- <input type="text" name="emailId"
- value={this.state.emailId}
- onChange={this.handleChange}
- placeholder="Your email id.."
- className={emailIdErr ? ' showError' : ''} />
- {emailIdErr &&
- <div style={{ color: "red", paddingBottom: 10 }}>{emailIdErr}</div>
- }
-
- </div>
- <div>
- <label htmlFor="text">Birth Date</label>
- <input type="text" name="dob"
- value={this.state.dob}
- onChange={this.handleChange}
- placeholder="DD/MM/YYYY.."
- className={dobErr ? ' showError' : ''} />
- {dobErr &&
- <div style={{ color: "red", paddingBottom: 10 }}>{dobErr}</div>
- }
- </div>
- <div>
- <label htmlFor="gender">Gender</label>
- <select name="gender" onChange={this.handleChange}
- className={genderErr ? ' showError' : ''}
- value={this.state.gender} >
- <option value="select">--Select--</option>
- <option value="male">Male</option>
- <option value="female">Female</option>
- <option value="female">Other</option>
- </select>
- {genderErr &&
- <div style={{ color: "red", paddingBottom: 10 }}>{genderErr}</div>
- }
- </div>
- <div>
- <label htmlFor="phoneNumber">Phone Number</label>
- <input type="text" name="phoneNumber"
- onChange={this.handleChange}
- value={this.state.phoneNumber}
- placeholder="Your phone number.."
- className={phoneNumberErr ? ' showError' : ''} />
- {phoneNumberErr &&
- <div style={{ color: "red", paddingBottom: 10 }}>{phoneNumberErr}</div>
- }
- </div>
- <div>
- <label htmlFor="city">City</label>
- <select name="city"
- value={this.state.city}
- onChange={this.handleChange}
- className={cityErr ? ' showError' : ''} >
- <option value="select">--Select--</option>
- <option value="Pune">Pune</option>
- <option value="Mumbai">Mumbai</option>
- <option value="Hyderabad">Hyderabad</option>
- </select>
- {cityErr &&
- <div style={{ color: "red", paddingBottom: 10 }}>{cityErr}</div>
- }
- </div>
- <input type="submit" value="Submit" />
- </form>
- </div>
- </div >
- )
- }
- }
-
- export default AdmissionForm;
- After adding the above code into AdmissinForm.js file, Import AddmissinForm component into App.js file.
- import React, { Component } from 'react';
- import './App.css';
- import AdmissionForm from './AdmissionForm';
-
- export default class App extends Component {
- render() {
- return (
- <div className="content">
- <AdmissionForm />
- </div >
- );
- }
- }
- Now, run your application using following command
npm start -o
- Above command will open browser and your output should be like the below screen.
- Enter invalid data to check/fire validations for this form/ input fields. If you enter invalid data into form input fields then it will show you validation messages like below.
- If you provide the correct data to form input fields and pressthe submit button, then data/information gets stored successfully without prompting a validation message.
Summary
In this article, I have demonstrated how to implement form validation in ReactJS. Hopefully, it will help.