A
A
Artem Petrenko2016-03-31 10:23:36
JavaScript
Artem Petrenko, 2016-03-31 10:23:36

How to loop prompt with validation?

I warn you right away that the question is probably stupid :)
You need to enter a number, check if the user did not enter anything or entered an empty string, and beat prompt until he enters what is needed. Everything is ok here.
Then check for a number (please do not offer complex options for how else to check, because I am a noob). If not a number - then an alert with a message and a request to enter again. And so here null, an empty line and td accepts with ease. In principle, it is clear, because we overwrite the variable, but this point is still not clear.

var a = +prompt ("Enter the first number", ""); 
    while (a==undefined||a==null||a=='') { //тут проверка работает
      var a = +prompt ("Enter the first number", "");
    }

    while (isNaN(a*1)) { 
      alert("It's not a number!"); 
      var a = +prompt ("Enter the first number!", "");  //а вот тут уже спокойно принимает 
null и т.д. Не совсем понятно как тут тоже зациклить, если снова не прописывать while.
    }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
C
Cyber_bober, 2016-03-31
@Cyber_bober

Are you solving a learning problem or doing a project? do you need to perform a check and displays a dialog box if you entered not a number or an empty string?

D
DireX, 2016-03-31
@xDireX

Create a function with callback that will call itself on error and pass parameters to the desired function if the value is correct

// Функция при успешной проверки
var finishPromt = function(data){
  alert(data);
}

// Функция проверки
var checkPrompt = function (callkack){
  var a = prompt ("Please enter: 123", ""); 

  if(a != 123){
    checkPrompt(finishPromt);
  }else{
    callkack(a);
  }
}

// Вызов функции проверки
checkPrompt(finishPromt);

P
polar-bear, 2016-03-31
@polar-bear

var num = prompt ("Enter the first number", "");
while (!isNumeric(num)) {
    alert("It's not a number!");
    num = prompt ("Enter the first number", "");
}

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

D
Denis, 2016-04-01
@denilenko

I think among npm packages you can find something suitable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question