Simple Javascript prompt validation loop not working

387 views Asked by At

I cant seems to get this to work.

<script language="JavaScript">
var name = null;
do
{
    var name = prompt("Please enter your full name","");
}
while(name != null);
</script>
2

There are 2 answers

4
Bradley Flood On BEST ANSWER

I would use a boolean value:

var name = false;
do
{
    name = prompt("Please enter your full name",'');
}
while(!name); // While name is not true

Also you were re-declaring the name var again on within the do loop, remove the var in the loop.

0
Arun P Johny On

When you enter a blank string and press OK, it returns a empty string not null, null is returned only when you press cancel.

You can test for truthyness of the returned value

var name = null;
do {
  name = prompt("Please enter your full name");
  console.log(name)
}
while (!name);
console.log('done', name)