How To Validate Password and Confirm Password in React JS

Udemezue John - Oct 7 - - Dev Community

Introduction.

When building web applications with React, creating a smooth and secure user experience is essential, especially when handling sensitive information like passwords.

One of the most common tasks in user authentication is validating the "password" and "confirm password" fields to ensure they match, helping users avoid potential mistakes when signing up or changing their password.

In this guide, I'll walk through how to implement password validation and ensure that the confirmation password matches in a React application.

Why Password Validation is Important.

Poor password policies are one of the leading causes of security breaches.

According to the 2023 Verizon Data Breach Investigations Report, compromised credentials contributed to over 80% of data breaches globally.

Proper validation helps prevent these breaches by ensuring strong passwords that meet complexity requirements.

Additionally, matching the password and confirm password fields helps users avoid mistakes, reducing frustration.

How Do I Validate Password and Confirm Password in React JS?

Handling password validation is one of the critical tasks when building web applications.

Users expect security and usability, and validating a password and its confirmation are key parts of this.

Ensuring both fields are validated in real-time improves the user experience while protecting sensitive information.

Let me walk you through how I implement password and confirm password validation in a React.js application.

To demonstrate password validation in React, I’ll start with a simple form that has two fields: "Password" and "Confirm Password." I'll focus on checking:

  • If the password meets basic security criteria.
  • If the password matches the confirm password field.

For simplicity, I'll use basic React hooks (useState) and JavaScript without external libraries.

Step 1: Setting Up the Form Component.

I’m assuming you already have a React project set up. If not, you can create one quickly by running:

npx create-react-app password-validation

Enter fullscreen mode Exit fullscreen mode

Once you have the project ready, I’ll create a new component, PasswordForm.js.

The form will have two input fields for the password and confirm password, and some validation logic.

import React, { useState } from "react";

const PasswordForm = () => {
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleConfirmPasswordChange = (e) => {
    setConfirmPassword(e.target.value);
  };

  return (
    <div>
      <form>
        <div>
          <label>Password</label>
          <input
            type="password"
            value={password}
            onChange={handlePasswordChange}
          />
        </div>
        <div>
          <label>Confirm Password</label>
          <input
            type="password"
            value={confirmPassword}
            onChange={handleConfirmPasswordChange}
          />
        </div>
        {error && <p style={{ color: "red" }}>{error}</p>}
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default PasswordForm;

Enter fullscreen mode Exit fullscreen mode

Step 2: Password Validation Logic.

Now that I have the form set up, it’s time to implement the validation logic.

The goal is to ensure that the password meets basic security requirements such as minimum length, use of upper and lower case letters, numbers, and special characters. I'll also ensure the two passwords match.

Here’s the validation logic I'll use:

  • Minimum length: At least 8 characters.
  • Complexity: Must contain uppercase, lowercase, a number, and a special character.

To achieve this, I'll add a validatePassword function.

const validatePassword = (password) => {
  const minLength = password.length >= 8;
  const hasUpperCase = /[A-Z]/.test(password);
  const hasLowerCase = /[a-z]/.test(password);
  const hasNumber = /\d/.test(password);
  const hasSpecialChar = /[!@#$%^&*]/.test(password);

  return minLength && hasUpperCase && hasLowerCase && hasNumber && hasSpecialChar;
};

Enter fullscreen mode Exit fullscreen mode

This function checks the password for the required conditions. If any condition fails, it returns false.

Step 3: Confirm Password Validation.

For confirming passwords, I simply compare the two fields, ensuring they are identical.

In the form’s handleSubmit function, I’ll check both the password validation and the matching of passwords.

const handleSubmit = (e) => {
  e.preventDefault();

  if (!validatePassword(password)) {
    setError(
      "Password must be at least 8 characters long and contain an uppercase letter, a lowercase letter, a number, and a special character."
    );
    return;
  }

  if (password !== confirmPassword) {
    setError("Passwords do not match.");
    return;
  }

  setError("");
  // Proceed with form submission (e.g., sending data to the backend)
};

Enter fullscreen mode Exit fullscreen mode

I call this handleSubmit when the user clicks the submit button. If the password is invalid or the passwords don’t match, an error message is displayed. Otherwise, the form submits.

Step 4: Connecting the Logic to the Form.

I now need to wire up the validation with the form. Here’s the updated PasswordForm component:

import React, { useState } from "react";

const PasswordForm = () => {
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");

  const validatePassword = (password) => {
    const minLength = password.length >= 8;
    const hasUpperCase = /[A-Z]/.test(password);
    const hasLowerCase = /[a-z]/.test(password);
    const hasNumber = /\d/.test(password);
    const hasSpecialChar = /[!@#$%^&*]/.test(password);

    return minLength && hasUpperCase && hasLowerCase && hasNumber && hasSpecialChar;
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!validatePassword(password)) {
      setError(
        "Password must be at least 8 characters long and contain an uppercase letter, a lowercase letter, a number, and a special character."
      );
      return;
    }

    if (password !== confirmPassword) {
      setError("Passwords do not match.");
      return;
    }

    setError("");
    alert("Password is valid and matches!");
    // Here, I could proceed with form submission to the backend
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Password</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        <div>
          <label>Confirm Password</label>
          <input
            type="password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
          />
        </div>
        {error && <p style={{ color: "red" }}>{error}</p>}
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default PasswordForm;

Enter fullscreen mode Exit fullscreen mode

Step 5: User Experience Enhancements.

For a more user-friendly experience, I can provide real-time feedback as the user types.

Instead of waiting for the form submission, I can validate the password dynamically and show warnings instantly.

To do this, I’ll modify the handlePasswordChange and handleConfirmPasswordChange functions to check validation as the user types:

const handlePasswordChange = (e) => {
  const value = e.target.value;
  setPassword(value);

  if (!validatePassword(value)) {
    setError(
      "Password must be at least 8 characters long and contain an uppercase letter, a lowercase letter, a number, and a special character."
    );
  } else {
    setError("");
  }
};

const handleConfirmPasswordChange = (e) => {
  const value = e.target.value;
  setConfirmPassword(value);

  if (password !== value) {
    setError("Passwords do not match.");
  } else {
    setError("");
  }
};

Enter fullscreen mode Exit fullscreen mode

Now, as the user enters a password or confirms it, the errors will appear or disappear in real-time. This makes for a more interactive and responsive form.

Conclusion.

Validating passwords and their confirmation is essential for creating secure and user-friendly applications.

By adding real-time validation in React.js, I ensure that users create secure passwords while reducing friction during signup or password updates.

Password validation can also be extended further with more complex checks or integrated with external libraries like Formik or Yup for even more flexibility.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player