Michael M
Michael M

Reputation: 11

how to check if an input is a number in js

here is the code I've been working on.

var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
    var askFirstName = prompt("What is your first name?");
    var askLastName = prompt("What is your last name" + " " +       titleCase(askFirstName) + "?");
    var askAge = prompt("How old are you" + " " + titleCase(askFirstName) +  " " + titleCase(askLastName) + "?");

        if(askAge != int) {
            alert("Not a valid input")

        };

    return {
        firstName: titleCase(askFirstName),
        lastName: titleCase(askLastName),
        age: askAge
    };
};
function titleCase(string) {
    return string.charAt(0).toUpperCase() + string.slice(1); 
};

for(var i = 0; i < amountOfUsers; i++) {
    storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);

I wondering how I can check the input of askAge to see if it equals a number.

I tried some code as you can see on lines 9-12 and I can't figure it out. I know it has to do something with typeof.

Thoughts?

Upvotes: 0

Views: 558

Answers (6)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

The cryptic answer:

var askAge = prompt("How old are you" + " " + titleCase(askFirstName) +  " " + titleCase(askLastName) + "?");
if(!Number.isInteger(Number.parseInt(askAge))) {
    alert("Not a valid input")
};

More:

You are partially correct in your assumption, you do have to check the type of the number to ensure that is is a number and also that it is an integer. How you actually DO that has several options. Here is one that should work.

You must determine if you wish to use Number() or Number.parseInt() as that determination will herein make a difference in the accepted values.

Given that, I choose to use the parseInt in this answer. I also constructed it to not accept 0 as a value for the number of users.

First we use or create the isInteger and parseInt in Number:

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};
Number.parseInt = Number.parseInt || parseInt;

Declare our other functions: (commented)

// this will error out if "Cancel" on the prompt is clicked (null is passed in mystring)
function titleCase(mystring) {
  return mystring.charAt(0).toUpperCase() + mystring.slice(1);
}

function returnUserInput() {
  var isValid = false;
  var askFirstName = "";
  var askLastName = "";
  var askAge = null;
  do {
    askFirstName = prompt("What is your first name?"); // currently accepts " " as a valid name
    askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?"); // accepts " " as a valid name
    askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
    isValid = Number.isInteger(Number.parseInt(askAge));
    if (!isValid) {
      alert("Not a valid input");
    }
  } while (!isValid); // accepts 0 and negative values as age
  return {
    firstName: titleCase(askFirstName),
    lastName: titleCase(askLastName),
    age: Number.parseInt(askAge) // was using the unparsed string "4' if 4 was entered
  };
}

Use the functions:

var storeUsersInfo = [];
var amountOfUsers = 0;
var enteredCount = 0;
do {
  amountOfUsers = prompt("How many users do you want?");
  enteredCount = Number.parseInt(amountOfUsers, 10);// parse it
} while (!(Number.isInteger(Number.parseInt(amountOfUsers, 10))) && !enteredCount > 0)

amountOfUsers = enteredCount;

for (var i = 0; i < amountOfUsers; i++) {
  storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);// console.dir might also work (better?)

Upvotes: 0

Chiru
Chiru

Reputation: 4091

This can be solved using a combination of Number.isInteger and Number.parseInt. Both of which have been standardized in ES2015.

The following expression will check if the age is valid:

Number.isInteger(Number.parseInt(askAge));

Note that you'll have to parse the user input to an integer first; this can either result in a valid integer or in NaN.

If it is an integer, then Number.isInteger will make the expression true; otherwise, the parsed number was NaN and the expression will become false.

Upvotes: 1

gavgrif
gavgrif

Reputation: 15499

multiply it by 1 and if it returns NaN and is not the same as the original input- its not a number

        var askAge = prompt("How old are you" + " " + titleCase(askFirstName) +  " " + titleCase(askLastName) + "?");
        var askedAge=parseInt(askAge)*1;
          if(askedAge != askAge) {
              alert("Not a valid input");
            }

Upvotes: 1

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

try this

var check = /^[0-9]+$/;
var checkall = askAge.match(check);
if (!checkall){ 
                 alert("Not a valid input")
       }

Upvotes: 0

Marcin Strzyż
Marcin Strzyż

Reputation: 61

You could use

Number.isInteger(askAge)

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

Upvotes: 0

vibhav yadav
vibhav yadav

Reputation: 53

I think you can you this code,

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

Upvotes: 0

Related Questions