Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Alejandro Rodriguez
Alejandro Rodriguez
3,020 Points

Password Validation (while and if) conditions

Hello i try to practice all i learn and create valiation password that allow user to time only 3 time the password before get an alert... but the if counter > 3 is not working... any help will be apreciated.

var ingresar_clave = prompt('Ingrese su contraseña');
var password = 'cometa';
var contador = 0;
if (contador > 3){
  alert('Ha sobrepasado el limite de intentos posibles. Hasta la vista baby!!!');
} else {
contador += 1;
while (ingresar_clave !== password){
  ingresar_clave = prompt ('Clave incorrecta! Intente de nuevo.');
}
}
document.write ('<h2>Bienvenido. Su password ' + password + ' es correcto! </h2>')

2 Answers

Steven Parker
Steven Parker
231,007 Points

The counting and count-checking needs to be done inside the loop, plus you need to break the loop when the limit is exceeded and then check the count before printing the welcome:

var ingresar_clave = prompt('Ingrese su contraseña');
var password = 'cometa';
var contador = 0;
while (ingresar_clave !== password) {
  contador += 1;
  if (contador >= 3) {
    alert("Ha sobrepasado el limite de intentos posibles. Hasta la vista baby!!!");
    break;
  } else {
    ingresar_clave = prompt("Clave incorrecta! Intente de nuevo.");
  }
}
if (contador < 3)
  document.write("<h2>Bienvenido. Su password " + password + " es correcto! </h2>");
Andrey Misikhin
Andrey Misikhin
16,529 Points

Your counter must be inside while cycle and contador must be less then 3. Better way for this code wiil be using of do .. while.

var password = 'cometa';
var contador = 0;
alert('Ha sobrepasado el limite de intentos posibles. Hasta la vista baby!!!');

do {
  ingresar_clave = prompt ('Clave incorrecta! Intente de nuevo.');
  contador += 1;
} while (ingresar_clave !== password && contador < 3)

document.write('<h2>Bienvenido. Su password ' + password + ' es correcto! </h2>');