2

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/

3
  • You did not use parseFloat on the prompt in the while loop in Solution 1 Commented Sep 7, 2022 at 15:27
  • It never exits the while loop in solution 2 because you check if the width is less than or equal to 0. You are also checking if the width is a number with !isNaN in the while condition. Commented Sep 7, 2022 at 15:28
  • there are 2 parts, the JS code part and the HTML interface part. With HTML5 the interfaces have evolved and make it possible to avoid having to always re-coding input controls. in your case you have to use a input type range Commented Sep 7, 2022 at 15:36

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.