0

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?

Michael M
  • 1
  • 6
  • Possible duplicate of [Validate decimal numbers in JavaScript - IsNumeric()](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – Mark Schultheiss Apr 26 '16 at 22:16

6 Answers6

1

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");
            }
gavgrif
  • 15,194
  • 2
  • 25
  • 27
  • What if user gives input as empty string " " or NaN – brk Apr 26 '16 at 03:49
  • can i say " input validation"? - either way - the outcome will be the same - its nay a number and should not be permitted – gavgrif Apr 26 '16 at 03:52
  • That didn't do anything. – Michael M Apr 26 '16 at 03:53
  • try .... if(parseInt(askAge)... also you should put your return into an else statement - otherwise it will return the details irrespective of the alert – gavgrif Apr 26 '16 at 03:56
  • @user2181397 - read it - still say its the role of input validation to sort out the acceptable inputs – gavgrif Apr 26 '16 at 03:59
  • @Michael M - does it give you the alert to say its not a number? does it then continue with the function after you click ok on that alert? – gavgrif Apr 26 '16 at 05:21
  • @gavgrif - It doesn't even alert me if I put in a word etc. And yeah it just loads the other function. but I get no alert – Michael M Apr 26 '16 at 20:29
  • This answer is wrong on so many levels. You can't use `==` to check for `NaN` in JavaScript. The `if` body is never executed. Also, `NaN` is an actual literal, not a string in JavaScript. – Chiru Apr 26 '16 at 22:12
1

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.

Chiru
  • 3,661
  • 1
  • 20
  • 30
  • and for IE you need `Number.isInteger = Number.isInteger || function(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; };` and `Number.parseInt = parseInt;` – Mark Schultheiss Apr 26 '16 at 22:22
  • @MarkSchultheiss You don't; nowadays, you usually transpile your code to support old browsers. Have a look at [babel](https://babeljs.io). – Chiru Apr 26 '16 at 22:23
  • @MarkSchultheiss Agreed! – Chiru Apr 26 '16 at 22:28
0

I think you can you this code,

function isNumeric(x) {
  return !isNaN(parseFloat(x)) && isFinite(x);
}
vibhav yadav
  • 53
  • 1
  • 11
0

You could use

Number.isInteger(askAge)

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

0

try this

var check = /^[0-9]+$/;
var checkall = askAge.match(check);
if (!checkall){ 
                 alert("Not a valid input")
       }
Mohammed Elhag
  • 4,272
  • 1
  • 10
  • 18
  • What does the value of check mean? – Michael M Apr 26 '16 at 03:58
  • the value means the numbers only without any kind of characters so when you match it with your input value that means your input value will match this expression only when it is number , so i wrote if(!checkall) that means if not match , alert so and so – Mohammed Elhag Apr 26 '16 at 04:14
0

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?)
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • somewhat, with comments :) for reasons; without the loops it will fail oddly and keep invalid entries. Use just the check OR simply what you wish of this. Alerting and keep going did not seem to be optimal – Mark Schultheiss Apr 27 '16 at 04:10
  • Would you mind making something for when it asks for your age and if you type in someone invalid like a letter instead of a number it will keep on asking you for your age and saying invalid input for evey time you don't enter a number. Like in a for loop @Mark Schultheiss – Michael M Apr 27 '16 at 04:17
  • So just use the `Number.isInteger(Number.parseInt(askAge))` in your if statement if that is all you desire. Note that this site is also about learning/teaching and I do learn a lot from other users "more complete" replies. Lots of questions might otherwise simply have "yes" or "no" or "because your code is wrong" answers and be less of value – Mark Schultheiss Apr 27 '16 at 04:21
  • your talking about the if statement in my og code right? – Michael M Apr 27 '16 at 04:26
  • Added cryptic answer. Note that I also often write a bit more complex answers when other challenges in code are demonstrated as you see reflected here. Not a judgement, we all started with less knowledge as we learned. Without the `Number.isInteger` function you would not see the "typeof" you referred to. – Mark Schultheiss Apr 27 '16 at 04:27