When a user enters and re-enters their password, I have a form that checks the strength of the password and displays text accordingly. However, I noticed that if a user makes a mistake and uses the backspace to re-enter the password, the text from data-text
is no longer displayed because the content
property from the CSS is removed, possibly due to the backspace action. I have been unable to find a solution to prevent this removal.
// Password field
self.addEventListener("keyup", () => {
let val = self.value;
testPasswordStrength(val);
});
// check password strength
const testPasswordStrength = (value) => {
const strengthText = document.getElementsByClassName('js-password-strength')[0];
const strongRegex = new RegExp(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[=/\()%ยง!@#$%^&*])(?=.{8,})'
),
mediumRegex = new RegExp(
'^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})'
);
if (value) {
if (strongRegex.test(value)) {
strengthText.setAttribute('data-validation-text', strengthText.dataset.textStrong);
return "strong";
} else if (mediumRegex.test(value)) {
strengthText.setAttribute('data-validation-text', strengthText.dataset.textGood);
return "medium";
} else {
strengthText.setAttribute('data-validation-text', strengthText.dataset.textDefault);
return "weak";
}
} else {
strengthText.classList.add("d-none");
}
};
content: attr(data-validation-text);
<div class="js-password-strength" data-validation-text data-text-default="Password must be 8+ characters" data-text-good="Good password" data-text-strong="Great password">
</div>