The following is React code that checks at least two combinations of uppercase letters, numbers, and special characters when changing passwords. Whenever the value entered in the password input field is changed, this code checks whether some of uppercase letters, numbers, and special characters are included, and exposes an error message according to conditions.
import React, { useState } from "react";
function PasswordChecker() {
const [password, setPassword] = useState("");
const [valid, setValid] = useState(false);
function handleChange(event) {
setPassword(event.target.value);
// 비밀번호에 대문자, 숫자, 특수문자 중 2개 이상의 조합이 있는지 검사하고,
// 동시에 비밀번호의 최소 길이가 8자리 이상인지도 검사합니다.
const regex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/;
setValid(regex.test(event.target.value));
}
return (
<div>
<label>
Password:
<input type="password" value={password} onChange={handleChange} />
</label>
{password && !valid && (
<p style={{ color: "red" }}>
Password must contain at least 2 of the following: uppercase
letters, digits, or special characters, and must be at least 8
characters long.
</p>
)}
</div>
);
}
export default PasswordChecker;
In the code above, the regular expression regex used is changed. The regular expression checks if the password contains at least 8 characters, with at least two combinations of uppercase letters, lowercase letters, numbers, and special characters. The regular expressions are (?=.[A-Za-z]), (?=.\d), (?=.[!@#$%^&])
, respectively. Checks if you have at least one of the special characters. After that, [A-Za-z\d!@#$%^&*]{8,}
is the part that checks for a string of 8 or more digits among those characters.