Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Simple Form Validation In Reactjs Example

This tutorial explains how to validate simple user registration form in reactjs. Form validation is most important part in web development, through which we can restrict invalid entries and validate user details in some extent by using valid sets of checkpoints or validation rules.
Here we are using simple user registration form and performing Client Side Validation using RegisterForm Component. Let see the React user registration form below :


So, Here when user click on register button without entering any fields details, then it will show below error messages.(Refer the below screenshot)
Apart from above Form Error Message Validation, we have covered some other checkpoints or validation rules, Lets see the some more validation one by one.

  1. Name Field : This field accept only valid user name, which include user First, Middle and Last name.
  2. Email Field : This field accept only valid Email address of user.
  3. Mobile Field : This field accept valid 10 digit mobile number of user.
  4. Password Field : This field accept only accept user password details. This validation makes the user password very strong and which complies below format :
  •  Must be at least 8 characters
  • At least 1 special character from @#$%&
  • At least 1 number, 1 lowercase, 1 uppercase letter

ReactJs Form Validation 

Lets see the below source code, which help you to build more understanding to create user registration form.

Project Structure :
Lets see the project structure for user registration form :


RegisterForm.js
This is a RegisterForm Component, it helps to render  user registration form and validate the user details by using simple java script validation. Lets see the complete source code.

Here we are storing the user fields details and error message in state.
1. fields: {} : Storing user details (i.e : Name, Mobile, Email and Password) from the user registration form.
2. errors: {} : Storing the error messages for different user fields and it helps to display error messages for different user fields by using state. 

Lets discuss about the functions :
1. handleChange(e) : This function helps to store user details in state (i.e : fields: {} ).
2. validateForm() : This is a core part of form validation. It helps to validate the user details for various fields present in user registration form and display the error message for corresponding fields if any.
3. submituserRegistrationForm(e) : This function validate the user details by calling validateForm() function and clear the user form details when user form details is valid.

import React from 'react';
import './style.css';


class RegisterForm extends React.Component {
constructor
() {
super();
this.state = {
fields
: {},
errors
: {}
}

this.handleChange = this.handleChange.bind(this);
this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this);

};

handleChange
(e) {
let fields = this.state.fields;
fields
[e.target.name] = e.target.value;
this.setState({
fields
});

}

submituserRegistrationForm
(e) {
e
.preventDefault();
if (this.validateForm()) {
let fields = {};
fields
["username"] = "";
fields
["emailid"] = "";
fields
["mobileno"] = "";
fields
["password"] = "";
this.setState({fields:fields});
alert
("Form submitted");
}

}

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(/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%&]).*$/)) {
formIsValid
= false;
errors
["password"] = "*Please enter secure and strong password.";
}
}

this.setState({
errors
: errors
});
return formIsValid;


}



render
() {
return (
div id="main-registration-container">
div id="register">

Registration pageh3>
form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm} >
Namelabel>
input type="text" name="username" value={this.state.fields.username} onChange={this.handleChange} />
div className="errorMsg">{this.state.errors.username}div>
Email ID:label>
input type="text" name="emailid" value={this.state.fields.emailid} onChange={this.handleChange} />
div className="errorMsg">{this.state.errors.emailid}div>
Mobile No:label>
input type="text" name="mobileno" value={this.state.fields.mobileno} onChange={this.handleChange} />
div className="errorMsg">{this.state.errors.mobileno}div>
Passwordlabel>
input type="password" name="password" value={this.state.fields.password} onChange={this.handleChange} />
div className="errorMsg">{this.state.errors.password}div>
input type="submit" className="button" value="Register"/>
form>
div>
div>

);
}


}


export default RegisterForm;

style.css
It consists of style sheet design for user registration form.
#register, #login {
width
: 300px;
border
: 1px solid #d6d7da;
padding
: 0px 15px 15px 15px;
border
-radius: 5px;
font
-family: arial;
line
-height: 16px;
color
: #333333;
font
-size: 14px;
background
: #ffffff;
margin
: 100px auto;
}

form label
, form input {
display
: block;
//margin-bottom: 10px;
width
: 90%
}

form input
{
padding
: 10px;
border
: solid 1px #BDC7D8;

}

.button {
background
-color: #00BFFF;
border
-color: #3ac162;
font
-weight: bold;
padding
: 12px 15px;
color
: #ffffff;
}

.errorMsg {
color
: #cc0000;
margin
-bottom: 12px;
}

.sucessMsg {
color
: #6B8E23;
margin
-bottom: 10px;
}

index.js
This is a main component which helps to display the user registration form. Here we are appending the "user registration from" in div tag whose ID value is "root"


This post first appeared on Learn Programming, please read the originial post: here

Share the post

Simple Form Validation In Reactjs Example

×

Subscribe to Learn Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×