2008年1月2日 星期三

JavaScript : isNumberic

method 1 :
isNaN()
return false : "-0.5",-100
return true : "string"

method 2 :
check positive Numberic
var ValidChars = "0123456789.-";
reference from http://www.codetoad.com/javascript/isnumeric.asp

The simplest way to check whether the details entered in a text field are numeric is to to loop through the string and compare each character to a pre-defined list of acceptable characters.

In this function, we've allowed decimal points and numbers nought through 9.

We use two methods to help us here : the charAt and indexOf.

Using the charAt method, we can find out which character is filling a designated position within a string. We then use the indexOf method to search our ValidChars list of valid characters. If it doesn't exist, (if ValidChars.indexOf(Char) == -1) this means the user has entered an invalid character. Here's the full function.


function IsNumberic(sText)
{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;


for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}
return IsNumber;

}

沒有留言:

關於我自己

Aspire freedom , Hope to do Soming make self complete ~