1

I am currently taking input in a text-box and on-submit, I am validating the input, the input needs to be a number greater than 0, it should be integer and not contain decimal point. The problem is I am not able to find any method by which we can detect it is integer or contains decimal point. Here is the code I am using.

    txt[5] = $(this).parents('p').find('input:text').val();
    if (txt[5] == "" || isNaN(txt[5]) || txt[5] <= 0) 
    {
        alert("Incorrect Quantity");
        return false;
    }

Basically as you see I am validating the input given by user, I want to show them a message if the input is wrong, so I am currently using txt[5]%1!=0 to make sure only INT is allowed, but I am open to new answers.

Ankur
  • 75
  • 2
  • 9
  • 3
    Why not simply use `parseInt()`? It truncates floats and 'unparseable' input will return `NaN`. – Kiruse Oct 20 '13 at 19:12
  • possible duplicate of [How to check if a number is float or integer?](http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer) – Felix Kling Oct 20 '13 at 19:13
  • @FelixKling: Bear in mind that the answer to that dupe will not work if the supplied argument is a string, because `typeof "5"` is `string`. – Matt Ellen Oct 20 '13 at 19:20
  • @MattEllen: I don't think it's very difficult to adjust the solution. – Felix Kling Oct 20 '13 at 19:39

3 Answers3

4

The simplest way is to parse the text as a Number, coerce to integer, and see if they are equal:

var numbertxt5 = Number(txt[5]);
if(numbertxt5 | 0 == numbertxt5) { /* int */
} else if (!isNaN(numbertxt5)) { /* float */
} else { /* not a number */
SheetJS
  • 22,470
  • 12
  • 65
  • 75
3
txt[5] = parseInt($(this).parents('p').find('input:text').val(), 10);

This won't validate the number (see Nirk's answer for that), but if it's not an int, it will be converted to one.

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
3

That is because JavaScript has only one numerical type called number. It is neither int nor float, but it behaves like both at a time. However, you do have two methods that you can use for this parseInt and parseFloat.

var result = parseInt($(this).parents('p').find('input:text').val());
txt[5] = result;

Using parseFloat is similar. Eg.

var result = parseFloat($(this).parents('p').find('input:text').val());
txt[5] = result;

The second example is not what you want but it is here just for your reference.

UPDATE: @bfavaretto made a good point with using radix which I omitted in parseInt. Have a look at this page for reference http://www.w3schools.com/jsref/jsref_parseint.asp

Huske
  • 9,186
  • 2
  • 36
  • 53