How To Validate Username And Password In React JS

Websolutionstuff | Sep-13-2022 | Categories : React JS

In this article, we will see how to validate username and password in react js. In this example, we will validate the user name, email address, and password. You can learn how to validate a form in react js. Also, we will new react js project and import bootstrap for better UI.

So, let's see the username and password validation in react js and login form validation in react js.

Step 1: Install React App

In this step, we will create react application using the following command.

npx create-react-app my-app

 

 

Step 2: Create LoginForm Component

Now, we will create an App.js component file. In this file, we will write the login form validation.

src/App.js

import React from "react";
import "./styles.css";

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

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    let input = this.state.input;
    input[event.target.name] = event.target.value;

    this.setState({
      input
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    if (this.validate()) {
      console.log(this.state);

      let input = {};
      input["username"] = "";
      input["email"] = "";
      input["password"] = "";
      input["confirm_password"] = "";
      this.setState({ input: input });

      alert("Form is submitted");
    }
  }

  validate() {
    let input = this.state.input;
    let errors = {};
    let isValid = true;

    if (!input["username"]) {
      isValid = false;
      errors["username"] = "Please enter your username.";
    }

    if (typeof input["username"] !== "undefined") {
      const re = /^\S*$/;
      if (input["username"].length < 6 || !re.test(input["username"])) {
        isValid = false;
        errors["username"] = "Please enter valid username.";
      }
    }

    if (!input["email"]) {
      isValid = false;
      errors["email"] = "Please enter your email Address.";
    }

    if (typeof input["email"] !== "undefined") {
      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(input["email"])) {
        isValid = false;
        errors["email"] = "Please enter valid email address.";
      }
    }

    if (!input["password"]) {
      isValid = false;
      errors["password"] = "Please enter your password.";
    }

    if (!input["confirm_password"]) {
      isValid = false;
      errors["confirm_password"] = "Please enter your confirm password.";
    }

    if (typeof input["password"] !== "undefined") {
      if (input["password"].length < 6) {
        isValid = false;
        errors["password"] = "Please add at least 6 charachter.";
      }
    }

    if (
      typeof input["password"] !== "undefined" &&
      typeof input["confirm_password"] !== "undefined"
    ) {
      if (input["password"] != input["confirm_password"]) {
        isValid = false;
        errors["password"] = "Passwords don't match.";
      }
    }

    this.setState({
      errors: errors
    });

    return isValid;
  }

  render() {
    return (
      <div class="main-div">
        <h5>
          How To Validate Username And Password In React JS - Websolutionstuff
        </h5>
        <form onSubmit={this.handleSubmit}>
          <div class="form-group">
            <label for="username">Username:</label>
            <input
              type="text"
              name="username"
              value={this.state.input.username}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter username"
              id="username"
            />

            <div className="text-danger">{this.state.errors.username}</div>
          </div>

          <div class="form-group">
            <label for="email">Email Address:</label>
            <input
              type="text"
              name="email"
              value={this.state.input.email}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter email"
              id="email"
            />

            <div className="text-danger">{this.state.errors.email}</div>
          </div>

          <div class="form-group">
            <label for="password">Password:</label>
            <input
              type="password"
              name="password"
              value={this.state.input.password}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter password"
              id="password"
            />

            <div className="text-danger">{this.state.errors.password}</div>
          </div>

          <div class="form-group">
            <label for="password">Confirm Password:</label>
            <input
              type="password"
              name="confirm_password"
              value={this.state.input.confirm_password}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter confirm password"
              id="confirm_password"
            />

            <div className="text-danger">
              {this.state.errors.confirm_password}
            </div>
          </div>

          <input
            type="submit"
            value="Submit"
            class="btn btn-success submit_btn"
          />
        </form>
      </div>
    );
  }
}

export default LoginForm;

 

 

Step 3: Import Component

In this step, we will import the component into the index.js file. Also, we will import bootstrap.

src/index.js

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";
import "bootstrap/dist/css/bootstrap.css";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

 

 

Step 4: Add CSS

Now, we will add CSS to the styles.css file.

src/styles.css

.App {
  font-family: sans-serif;
  text-align: center;
}

.main-div {
  margin: 50px;
}

.submit_btn {
  margin-top: 20px;
}

h5 {
  margin-bottom: 20px;
}

input {
  margin: 10px 0 10px;
}

 

Step 5: Run the server

Now, we will run the server using the following command.

npm start

 

Output:

how_to_validate_username_and_password_in_react_js_output

 


You might also like:

Recommended Post
Featured Post
Laravel 9 Firebase Push Notification
Laravel 9 Firebase Push Notifi...

In this article, we will see a laravel 9 firebase push notification, a firebase notification through you can notify...

Read More

Sep-20-2022

Laravel 10 Multiple Image Upload Example
Laravel 10 Multiple Image Uplo...

In this article, we will see laravel 10 multiple image examples. Here, we will learn about how to upload multiple i...

Read More

Mar-17-2023

Laravel 9 Inner Join Query Example
Laravel 9 Inner Join Query Exa...

In this article, we will see laravel 9 inner join query example. Also, see how to join two tables in laravel 9. In larav...

Read More

Mar-30-2022

How To Disable Weekends In jQuery Datepicker
How To Disable Weekends In jQu...

In this tutorial, we will see how to disable weekend dates in jquery datepicker. In the date picker, the weeke...

Read More

Jun-27-2022