I'm doing a JS exercise where they ask me to enter a password with a requirement and that if the third time I try the goal wrong, you can't continue entering data in the input. The problem is that I have it with real-time validation, which until you enter the word correctly, is always invalid. I leave my code.
document
.getElementById('campo')
.addEventListener('input', function(evt) {
const campo = evt.target,
valido = document.getElementById('campoOK'),
regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$%*&\-\_])[A-Za-z\d$@$%*&\-\_]{8,16}$/;
if (regex.test(campo.value)) {
valido.innerText = "válido";
} else {
valido.innerText = "incorrecto";
}
});
You can do it with a
button
to validate the password, by adding a counter we will know how many attempts it takes, on the third wrong attempt the buttonvalidar
will be blocked.By adding a listener to the event
input
, what you do is evaluate each time there is a change in that field, in this case each key that is pressed.That is, if the partial text that you are writing does not validate, it will be counted as incorrect. As in your regex the minimum is 8 characters, it will always give invalid on the third key that we press, whatever it may be.
In addition to that, the counter should be off, so as not to reset the counter on every event. To make testing more comfortable, in the regex I put as good only if numbers are entered.