JSFiddle - React, Tailwind, and code Playground

by Allie Yu

JavaScript

import React from "react";

const PasswordStrength = ({ password }) => {
  const checkPasswordStrength = () => {
    const minLength = 8;
    const hasUpperCase = /[A-Z]/.test(password);
    const hasLowerCase = /[a-z]/.test(password);
    const hasDigit = /\d/.test(password);
    const hasSpecialChar = /[$#&_]/.test(password);
    const characteristicsMatched = [hasUpperCase, hasLowerCase, hasDigit, hasSpecialChar].filter(Boolean).length;

    if (password === "") {
      return { text: 'Enter a password', backgroundColor: '' }
    }

    if (characteristicsMatched >= 5 && password.length >= minLength) {
      return { text: 'Strong Password', backgroundColor: 'green' };
    } else if (characteristicsMatched >= 3) {
      return { text: 'Moderate Password', backgroundColor: 'orange' };
    } else {
      return { text: 'Weak Password', backgroundColor: 'red' };
    }
  }

  const { text, backgroundColor } = checkPasswordStrength();

  return (
    <div
      className="px-5 py-5"
      style={{
        backgroundColor: backgroundColor,
      }}
      data-testid="passwordStrengthDiv"
    >
      <h4
        style={{
          color: "white",
          textAlign: "center",
        }}
        data-testid="passwordStrengthText"
      >
        {text}
      </h4>
    </div>
  );
};

export default PasswordStrength;




const PasswordChecker = () => {
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);

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

  const handleShowPassword = () => {
    setShowPassword(!showPassword);
  };

  return (
    <div>
      <label>Password:</label>
      <input
        type={showPassword ? 'text' : 'password'}
        value={password}
        onChange={handlePasswordChange}
        placeholder="Enter your password"
      />
      <button onClick={handleShowPassword}>{showPassword ? 'Hide Password' : 'Show Password'}</button>
      <PasswordStrength...