Sunday, June 10, 2018

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 :
how to validate form in reactjs, form validation using react js, login form validation in react js


So, Here when user click on register button without entering any fields details, then it will show below error messages.(Refer the below screenshot)
how to validate form in reactjs, form validation using react js, login form validation in react js
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 Example

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 :
how to validate form in reactjs, form validation using react js, login form validation in react js


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">
        <h3>Registration page</h3>
        <form method="post"  name="userRegistrationForm"  onSubmit= {this.submituserRegistrationForm} >
        <label>Name</label>
        <input type="text" name="username" value={this.state.fields.username} onChange={this.handleChange} />
        <div className="errorMsg">{this.state.errors.username}</div>
        <label>Email ID:</label>
        <input type="text" name="emailid" value={this.state.fields.emailid} onChange={this.handleChange}  />
        <div className="errorMsg">{this.state.errors.emailid}</div>
        <label>Mobile No:</label>
        <input type="text" name="mobileno" value={this.state.fields.mobileno} onChange={this.handleChange}   />
        <div className="errorMsg">{this.state.errors.mobileno}</div>
        <label>Password</label>
        <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 javascript file, which helps to display/render the user registration form. Here we are appending the "user registration from" in div tag whose ID value is "root"
import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import RegisterForm from './registrationForm/RegisterForm';


ReactDOM.render(<RegisterForm /> , document.getElementById('root'));

registerServiceWorker();

Hope you like this simple form validation example :


Demo Link :

Download Link :
https://github.com/skptricks/react/tree/master/Form%20validation%20in%20reactjs


17 comments:

  1. Thank you. Found this resourceful.

    ReplyDelete
  2. was very useful thank you so much

    ReplyDelete
    Replies
    1. ./src/index.js
      Module not found: Can't resolve './registerServiceWorker'

      Delete
  3. simple and awesome example - Thank you so much

    ReplyDelete
  4. Its really very helpful, executed without any issue.

    ReplyDelete
  5. Thanks, its very Helpful. i want to validate multiple pages using one common validation page in Reactjs. (if same field exist in all form like name, email...etc.) i want example like all validation code write only in common validation file.

    ReplyDelete
  6. this is really very helpful for me Thank u

    ReplyDelete
  7. Simple example, even beginners can understand easily. Thanks a lot!

    ReplyDelete
  8. Hi guys, i have built custom hook for easy form validation. i think it's gonna make your life a lot easier comes to form. you can leverage your html validation knowledge.
    Github: https://github.com/bluebill1049/react-hook-form
    Website: http://react-hook-form.now.sh

    ReplyDelete
  9. Simple form validation with React custom hook:
    https://github.com/bluebill1049/react-hook-form
    https://react-hook-form.now.sh

    ReplyDelete
  10. It is very helpful thanking you somuch

    ReplyDelete
  11. How to add onBlur for the above code.thanks in advance.

    ReplyDelete
  12. wow, such a nice description. Really helpful.

    ReplyDelete
  13. ./src/index.js
    Module not found: Can't resolve './registerServiceWorker' how to do can anyone rectify it

    ReplyDelete