ReactJS - Form

Hello everyone, Today we will learn how to validate a simple signup form in React JS.Form validation is the most important part of web development, through which we can restrict invalid entries and validate form details to some extent by using valid sets of checkpoints or validation rules.

Why form validation on the client-side? 

Form validation normally occurs on the server-side. This was really a lengthy process that used to put a lot of burden on the server. So, it will be a good choice if you add validation on the client side. Doing so improves application performance.

Here we are using a simple signUP form and performing Client Side Validation using SignUpForm Component. Let's see the React JS signUP form with error messages below:

Here we are validating the following entries,

  • Name
  • Email ID
  • Mobile Number
  • Password

Directory Structure:

Let's see the directory structure :



SignUpForm.jsx

This is a SignUpForm Component, it helps to render the signup form and validate the form details by using simple javascript validation.

import React from 'react';
import './style.css';
class SignUpForm extends React.Component {
constructor() {
super();
this.state = {
fields: {},
errors: {}
}
this.onChange = this.onChange.bind(this);
this.submitRegistrationForm = this.submitRegistrationForm.bind(this);
};
onChange(e) {
let fields = this.state.fields;
fields[e.target.name] = e.target.value;
this.setState({
fields
});
}
submitRegistrationForm(e) {
e.preventDefault();
if (this.validateForm()) {
let fields = {};
fields["username"] = "";
fields["emailid"] = "";
fields["mobileno"] = "";
fields["password"] = "";
fields["confirmPassword"] = "";
this.setState({ fields: fields });
alert("Ready to call server API")
}
}
validateForm() {
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
if (!fields["username"]) {
formIsValid = false;
errors["username"] = "*Please enter your username.";
}
if (typeof fields["username"] !== "undefined") {
if (!fields["username"].match(/^[a-zA-Z ]*$/)) {
formIsValid = false;
errors["username"] = "*Please enter alphabet characters only.";
}
}
if (!fields["emailid"]) {
formIsValid = false;
errors["emailid"] = "*Please enter your email-ID.";
}
if (typeof fields["emailid"] !== "undefined") {
//regular expression for email validation
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);
if (!pattern.test(fields["emailid"])) {
formIsValid = false;
errors["emailid"] = "*Please enter valid email-ID.";
}
}
if (!fields["mobileno"]) {
formIsValid = false;
errors["mobileno"] = "*Please enter your mobile no.";
}
if (typeof fields["mobileno"] !== "undefined") {
if (!fields["mobileno"].match(/^[0-9]{10}$/)) {
formIsValid = false;
errors["mobileno"] = "*Please enter valid mobile no.";
}
}
if (!fields["password"]) {
formIsValid = false;
errors["password"] = "*Please enter your password.";
}
if (typeof fields["password"] !== "undefined") {
if (!fields["password"].match(/^[A-Z]*$/)) {
formIsValid = false;
errors["password"] = "*Please enter secure and strong password.";
}
}
if (!fields["confirmPassword"]) {
formIsValid = false;
errors["confirmPassword"] = "*Please enter your password.";
}
if (fields["confirmPassword"] != fields["password"]) {
formIsValid = false;
errors["confirmPassword"] = "*Password Mismatch";
}
this.setState({
errors: errors
});
return formIsValid;
}
render() {
return (
<div id="main-registration-container">
<div id="register">
<h3>SingUp Form</h3>
<form method="post" name="userRegistrationForm"
onSubmit={this.submitRegistrationForm} >
<label>Name</label>
<input type="text" name="username" value=
{this.state.fields.username}
onChange={this.onChange} />
<div className="errorMsg">{this.state.errors.username}</div>
<label>Email ID:</label>
<input type="text" name="emailid"
value={this.state.fields.emailid}
onChange={this.onChange} />
<div className="errorMsg">{this.state.errors.emailid}</div>
<label>Mobile No:</label>
<input type="text" name="mobileno"
value={this.state.fields.mobileno}
onChange={this.onChange} />
<div className="errorMsg">{this.state.errors.mobileno}</div>
<label>Password</label>
<input type="password" name="password"
value={this.state.fields.password}
onChange={this.onChange} />
<div className="errorMsg">{this.state.errors.password}</div>
<label>Confirm Password</label>
<input type="password" name="confirmPassword"
value={this.state.fields.confirmPassword}
onChange={this.onChange} />
<div className="errorMsg">{this.state.errors.confirmPassword}</div>
<input type="submit" className="button"
value="Register" />
</form>
</div>
</div>
);
}
}
export default SignUpForm;

Here we are storing the form fields details and error message in the state.

  • fields: {}: Storing form details (Name, Mobile, Email, Password, and confirm password) from the signup form.
  • errors: {}: Storing the error messages for different form fields and helps to display error messages for different fields by using state.

functions

  • onChange(): This function helps to store form details in state (i.e : fields: {} ).
  • validateForm(): t helps to validate the form details for various fields present in the signup form and display the error message for corresponding fields if any.
  • submitRegistrationForm(): This function validate the form details by calling validateForm() function.


Download complete source code from our Github repository,
https://github.com/knowledgefactory4u/Node-js_knf.git


More related topics,

Java - Angular - VueJS - ReactJS

NodeJS - Angular - VueJS - ReactJS

Python - Flask  - Angular - VueJS - ReactJS

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete