How To Validate Password And Confirm Password In React JS

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

In this article, we will see how to validate password and confirm password in react js. Sometimes we need to add the password and confirm the password field in react js form. So, we will show you step-by-step how to validate password and confirm password. For password validation, we will use regular expressions and match password and confirm password in react js.

So, let's see password validation in react js using regex.

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 PasswordValidationForm Component

Now, we will create an App.js component file. In this file, we will write validation for password and confirm password.

src/App.js

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

class PasswordValidationForm 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["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["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["confirm_password"] = "Passwords don't match.";
      }
    }

    this.setState({
      errors: errors
    });

    return isValid;
  }

  render() {
    return (
      <div class="main-div">
        <h5>
          How To Validate Password And Confirm Password In React JS - Websolutionstuff
        </h5>
        <form onSubmit={this.handleSubmit}>         

          <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 PasswordValidationForm;

 

 

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_password_and_confirm_password_in_react_js

 


You might also like:

Recommended Post
Featured Post
How To Get Current Route In React JS
How To Get Current Route In Re...

As a web developer using React JS, I've come to appreciate the power and efficiency of this JavaScript library. Its...

Read More

Aug-11-2023

How To Validate Password And Confirm Password In React JS
How To Validate Password And C...

In this article, we will see how to validate password and confirm password in react js. Sometimes we need to add th...

Read More

Sep-14-2022

How To Get Last 15 Days Records In MySQL
How To Get Last 15 Days Record...

In this tutorial, we will see how to get the last 15 days records in MySQL PHP.  In PHP, you can use INTERVAL...

Read More

Feb-09-2022

How To Image Upload With Progress Bar Angular 15
How To Image Upload With Progr...

As an Angular 15 developer, I understand the importance of incorporating image upload functionality with a progress bar...

Read More

Jun-21-2023