Alfred
Alfred

Reputation: 21406

Simple number validation using JavaScript / jQuery

Is there any simple method in JavaScript / jQuery to check whether the variable is a number or not (preferably without a plugin)? I want to alert whether the variable is a number or not.

Thanks in advance...:)

Upvotes: 4

Views: 20246

Answers (5)

Mrinal Jha
Mrinal Jha

Reputation: 11

Can use below code for this. I would not rely on isNaN() completely. isNaN has shown inconsistent results to me (e.g - isNaN will not detect blank spaces.).

//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
    // Get the non Numeric char that was enetered
    var nonNumericChars = $(this).val().replace(/[0-9]/g, '');                                  
    if(nonNumericChars.length > 0)
        alert("Non Numeric Data entered");
});

Upvotes: 1

Corneliu
Corneliu

Reputation: 2942

I wouldn't recommend the isNaN function to detect numbers, because of the Java Script type coercion.

Ex:

isNaN(""); // returns false (is number), a empty string == 0
isNaN(true); // returns false (is number), boolean true == 1
isNaN(false); // returns false (is number), boolean false == zero
isNaN(new Date); // returns false (is number)
isNaN(null); // returns false (is number), null == 0 !!

You should also bear in mind that isNaN will return false (is number) for floating point numbers.

isNaN('1e1'); // is number
isNaN('1e-1'); // is number

I would recommend to use this function instead:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Upvotes: 19

Mamoon ur Rasheed
Mamoon ur Rasheed

Reputation: 317

use standard javascript functions

isNaN('9')// this will return false
isNaN('a')// this will return true

Upvotes: 0

Anupam
Anupam

Reputation: 8016

function isDigit(num) {
    if (num.length>1){return false;}
    var string="1234567890";
    if (string.indexOf(num)!=-1){return true;}
    return false;
}

You need to loop through the string and call this function for every character

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176956

Checking number using isNaN function

var my_string="This is a string";
if(isNaN(my_string)){
document.write ("this is not a number ");
}else{document.write ("this is a number ");
}

or

Check whether a number is an illegal number:

<script type="text/javascript">


    document.write(isNaN(5-2)+ "<br />");
    document.write(isNaN(0)+ "<br />");
    document.write(isNaN("Hello")+ "<br />");
    document.write(isNaN("2005/12/12")+ "<br />");

</script>

The output of the code above will be:

false
false
true
true 

Upvotes: 4

Related Questions