Praveen
Praveen

Reputation: 56501

How to validate the datatype of a variable in javascript?

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.

Upvotes: 1

Views: 15000

Answers (2)

user1786283
user1786283

Reputation:

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"

---EDIT---

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

Upvotes: 8

I Hate Lazy
I Hate Lazy

Reputation: 48761

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");
}

Upvotes: 1

Related Questions