Reputation: 21
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.
Upvotes: 2
Views: 1656
Reputation: 16020
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".
If you don't want a trailing decimal, then the @jakeclarkson's regex solution is better
Upvotes: 4
Reputation: 15042
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
Upvotes: 2