Input validation


#1

Hi, I’m working on this small project where I’m asking the user to enter a temperature in kelvin. I’ve completed it, but I wanted to go a step further and implement an input validation.

let kelvin;
do{
kelvin = prompt(“What is the temperture in Kelvin today?”)
}while(!(Number.isInteger(kelvin)));

I’m not sure if the code is correct because I just created it using my java knowledge, but I’m new to java script.
When I run the code it asks me for an input, but no matter what I enter it keeps asking me for an input. Also it freezes my entire browser, so i have to exit my browser.


#2

Hi @rengaragner,

This is because the return result of from a prompt is always a string type,

So what is assigned to kelvin variable is always string value instead of a number and the Number.isInteger() will always return false. !false equal to true which causes your while condition continue forever. One way to avoid this is to turn the string value into integer, you may look for this (depending on what you wish to achieve):

https://developer.mozilla.org/my/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Have fun coding! Cheers :slight_smile:


#3

Thanks a lot! That makes way more sense.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.