akcode17
akcode17

Reputation: 21

validating a function through a prompt

I created a prompt with a function. How do I validate the input with the prompt so that when a number is entered, if there is an error it will alert that the number is incorrect.

var value = parseInt(prompt("Enter a number with a decimal in the middle from 0-100" , ""));

var value = parseInt(prompt("Enter a number with a decimal in the middle from 0-100" , ""));

function validNumber(string) {

  let number = parseFloat(string, 10);

  if (number <= 0 || number >= 100) return false;

  if (string !== number.toFixed(2)) return false;

  return true;
}

Upvotes: 0

Views: 43

Answers (1)

Ele
Ele

Reputation: 33726

First, you don't need to convert to int before the validation because the function which validates the number is expecting a string.

If the returned value from the validation is false then we execute the function window.alert to show the error message.

function validNumber(string) {

  let number = Number(string, 10);

  if (number <= 0 || number >= 100) return false;

  if (string !== number.toFixed(2)) return false;

  return true;
}

var value = prompt("Enter a number with a decimal in the middle from 0-100" , "");

if (!validNumber(value)) alert('The entered number is incorrect!');
else console.log(`The entered string is a valid number '${value}'`);

Upvotes: 1

Related Questions