Issue
I am currently making password strength checker and I want to check the length of the password and determine the strength of the password. But I do not know how to check the length of the password so that it is like "between 5 and 10 words" or "between 20 to 30 words"
import React from "react";
import { useState } from "react";
const Password = () => {
const [password, setPassword] = useState("")
const HandleInputChange = (event) => {
setPassword(event.target.value)
}
const letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
const capsLetters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
const numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
const specialChar = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")"]
const slicedLetters = letters.slice(...letters)
const slicedCapsLetters = capsLetters.slice(...capsLetters)
const slicedNumbers = numbers.slice(...numbers)
const slicedSpecialChar = specialChar.slice(...specialChar)
const [passwordStrength, setPasswordStrength] = useState()
// I am working with this function
const StrengthCheck = () => {
if(password.includes(slicedLetters || capsLetters)) {
setPasswordStrength("Very Weak")
} else if(password.includes(slicedLetters && slicedNumbers || slicedCapsLetters)) {
setPasswordStrength("Weak")
} else if(password.includes(slicedLetters && slicedNumbers && slicedSpecialChar || slicedCapsLetters)) {
setPasswordStrength("Medium")
} else if(password.includes(slicedLetters && slicedCapsLetters && slicedSpecialChar || slicedNumbers)) {
setPasswordStrength("Strong")
} else if(password.includes(slicedLetters && slicedCapsLetters && slicedNumbers && slicedSpecialChar)) {
setPasswordStrength("Very Strong")
} else {
setPasswordStrength("Invalid Password to Check!")
}
}
return(
<div>
<h1>Password Strength Checker</h1>
<h3>Your Password</h3>
<input type={"text"} value={password} onChange={HandleInputChange}/>
<button onClick={StrengthCheck}>Confirm</button>
<h3>Password display:</h3>
<input type={"password"} value={password}/>
<br/>
<br/>
<hr/>
Your password strength is: <b>{passwordStrength}</b>
</div>
)
}
export default Password
Solution
There are many ways to do that. Your StrengthCheck function is not perfectly shaped and for considering the length you can create an array something like this,
const LengthChecker = [10,20,30,40,50]
After this, You can check this by,
var length = text.length;
var _index;
LengthChecker.map((item, index) => {
if(length < item){
_index = index;
break;
}
}
});
console.log(LengthChecker(_index)
Answered By - Usama Shahid
Answer Checked By - - Jay B. (ReactFix Admin)