2

I need to validate textbox entry. It should allow only integers as entityframework fails if user enters characters in this field during binding.

Here is problem:

When user enters 10-d in this field, parseFloat returns true as it takes 10 as number and ignores the rest of values. While IMO it should throw NAN error as input text can not be converted to float.

Please see following samples and you can play with it. http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_parsefloat

The one i am interested it to get NAN for 40 Years input in examples above.

document.write(parseFloat("40 years") + "<br />");

Let me know if i need to do some more verification.

Alex
  • 34,899
  • 5
  • 77
  • 90
PL0689
  • 21
  • 5
  • Use `$.isNumeric('10-d');` or `$.isNumeric('10 years')` both wil return false. – Prasenjit Kumar Nag Jun 26 '12 at 14:20
  • If you want integers try `parseInt("string",10)`. The second param is the radix which tells it what number base to use. In this case, base 10. – Jack Jun 26 '12 at 14:27
  • Actually `parseFloat('10-d')` returns `10` rather than `true`. Visit http://es5.github.com/#x15.1.2.3 to see how `parseFloat()` works. – Teemu Jun 26 '12 at 14:36

2 Answers2

4

Sounds like you want to use the isNaN function.

isNaN('40'); //false, as '40' is a number
isNaN('40 years'); //true, as '40 years' is not a number

Update

As noted, this does not check for integers. For that, you could use

function isInt(value) { 
  return !isNaN(value) && value % 1 === 0; 
}

This would return true for "40", 40, "40." and false for "40-d", "40.12", 40.12, "40 years".

jsFiddle Demo

If you don't want a trailing decimal, then the @jakeclarkson's regex solution is better

jackwanders
  • 15,612
  • 3
  • 40
  • 40
2

If you only want to allow integers then you could use:

function isInteger(str) {
    return /^[0-9]*$/.test(str);
}

isNaN will return false if you provide it with a decimal, i.e.

isNaN("3.14"); // false, i.e. it is a number

Whereas the isInteger() function above will work correctly, i.e.

isInteger("3.14"); // false
jabclab
  • 14,786
  • 5
  • 54
  • 51