using this we can show the password Strength based on the score and letters.
A password checker that evaluates the strength of a user’s password displays a warning message if the password is considered strong notify the user to update the password in the backend.
The criteria for strong password. Common criteria include:
- Minimum length (e.g., at least 8 characters)
- Inclusion of both uppercase and lowercase letters
- Inclusion of numbers
- Inclusion of special characters (e.g., !, @, #, $)
const calculateStrength = (password) => {
let strength = 0;
let message = '';
if (password.length >= 8) strength += 1;
if (/[A-Z]/.test(password) && /[a-z]/.test(password)) strength += 1;
if (/d/.test(password)) strength += 1;
if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength += 1;
if (!password) {
message = '';
} else if (password.length < 8) {
message = 'Password is too short. Kindly update your password.';
} else if ((!/[A-Z]/.test(password))||(!/[a-z]/.test(password))||(!/[0-9]/.test(password))||(!/[!@#$%^&*(),.?":{}|<>]/.test(password))) {
message = 'Password is week. Kindly update your password.';
}else if (strength === 4) {
message = 'Password is strong.';
}
return { strength, message };
};
const handlePasswordChange = (e) => {
const newPassword = e.target.value;
setPassword(newPassword);
const { strength, message } = calculateStrength(newPassword);
setPasswordStrength(strength);
setWeakPasswordWarning(message);
};
<input
id="password"
name="password"
type={showPassword ? "text" : "password"}
autoComplete="new-password"
required value={password}
onChange={handlePasswordChange}
placeholder="Password"
className="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"
/>
<Image width={12} height={12} src={showPassword ? "images/lock2.png" : "images/lock1.png"} alt="Eye Icon" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 transform -translate-y-1/3 w-6 cursor-pointer" />
</div>
<p className="text-sm text-gray-600 text-center">{weakPasswordWarning}</p>
{password&&(
<div className="flex justify-between m-0">
<div className={`w-1/4 h-2 rounded-full ${passwordStrength>=4? 'bg-cyan-900':passwordStrength>=1? 'bg-red-500':'bg-gray-300'}`}></div>
<div className={`w-1/4 h-2 rounded-full ${passwordStrength>=4? 'bg-cyan-900':passwordStrength>=2? 'bg-yellow-500':'bg-gray-300'}`}></div>
<div className={`w-1/4 h-2 rounded-full ${passwordStrength>=4? 'bg-cyan-900':passwordStrength>=3? 'bg-green-300':'bg-gray-300'}`}></div>
<div className={`w-1/4 h-2 rounded-full ${passwordStrength>=4? 'bg-cyan-900':'bg-gray-300'}`}></div>
</div>
)}