MichaelSTL
MichaelSTL

Reputation: 41

while loop to prompt for valid number input

Please help me fix my code so as to perform input validation from my prompt. I am a JavaScript beginner. I am trying to create a getWidth() and getLength() functions that would get input from a user. Later on the inputs would be used to calculate the area of a rectangle. It's a mini code just to validate the input the user is giving to these functions. Here is my first approach:

const getWidth = function () {
 
 // check if the number passed for width is valid a number
  let width;
  width = parseFloat(prompt('Enter the width of your rectangle '));
  while (typeof width !== 'number' || width <= 0 || !isNaN(width)) {
    width = prompt('Enter a valid value');
  }

  return width;
};

let newWidth = getWidth();
console.log(newWidth);


/****Solution no 2 **/
const getWidth = function () {
 
  // check if the number passed for width is valid a number
  
   let width;
   do{
    width = parseFloat(prompt('Enter the width of your rectangle '));
    if(typeof width === 'number' && width <= 0 && !isNaN(width)){
      return width;
    }
   }while(typeof width==='string' || width <= 0 || !isNaN(width) )
   
   return width;
 };

 
 let newWidth = getWidth();
console.log(newWidth);

/Solution 2 fails at while loop/

Upvotes: 2

Views: 739

Answers (1)

tenshi
tenshi

Reputation: 26324

Prompt the user for a number input, while their input is not a number.

For the prompt, we use yours:

width = parseFloat(prompt("Enter the width of your rectangle "));

For the other half, we use Number.isNaN(Number(width)).

This is just a simple and readable way to check if the input was a numeric string.

Number coerces its input to a number, or NaN if it's not possible, and we check if the result is NaN with Number.isNaN.

const getWidth = function () {
  let width;
  
  do {
    width = parseFloat(prompt("Enter the width of your rectangle "));
  } while (Number.isNaN(Number(width)));

  return width;
};

console.log(getWidth());

References:

Upvotes: 1

Related Questions