In Javascript, is there a way to check or validate the datatype of a variable? I need to allow users to enter float values in the textbox.
Thank you.
In Javascript, is there a way to check or validate the datatype of a variable? I need to allow users to enter float values in the textbox.
Thank you.
If you're dealing with literal notation only, and not constructors, you can use typeof:.
Example:
>var a = 1;
>var b = "asdasd";
>typeof(b);
"string"
>typeof(a);
"number"
To validate numbers or float values use:
function isNumber (n) {
return ! isNaN (n-0);
}
Example:
>var a = 1;
>isNumber(1);
True
Float Included, use parsefloat:
function isIntandFloat(n) {
return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
}
Or if you want just float use this:
function Float (n) {
return n===+n && n!==(n|0);
}
Example:
>var a = 0.34324324324;
>Float(a);
true
>var int = 3;
>Float(int);
false
A text box will always give you a string primitive value.
What you want is to see if the input can be converted from a string to a number. For this you can use parseFloat().
var num = parseFloat(textbox.value);
if (isNaN(num)) {
alert("Invalid input");
}
If you want more strict evaluation, use the Number function
var num = Number(textbox.value);
if (isNaN(num)) {
alert("Invalid input");
}
parseFloat() doesn't tell you if the entered value actually is a number, because parseFloat("123abc") returns 123. @Jeroen - that doesn't prevent pasting and drag'n'drop of invalid values.+textbox.value? It seems to fail on an input of "123abc" yet not need to create a Number object+ could be used too, but Number is a little clearer for a beginner. Using Number doesn't actually create an object. We still get the number primitive. It's only if new is used that we get the object wrapper. :-) es5.github.com/#x15.7.1