codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:


Home » Javascript » Article

Javascript IsNumeric Function

Article by:  Jeff Anderson  ( 1362 ) (2/26/2002)
Bookmark us now! Add to Favourites
Email a friend!Tell a friend
Sponsored by: FindMyHosting - Web Hosting Search
Summary: A javascript validation function to check whether the details entered by a user are numeric.
Viewed: 503481 times Rating (138 votes): 
 3.7 out of 5
 Rate this Article  Read Comments  Post Comments


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 IsNumeric(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;    }

To understand how to use the IsNumeric function to validate a form, see Form Validation function Page.







CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums
Rate this article:     Poor Excellent
View highlighted Comments
User Comments on 'Javascript Isnumeric function'
Posted by :  Archive Import (Anton) at 11:26 on Tuesday, August 06, 2002
Why go thru the trouble of writing your own function? isNaN works just fine for the same purpose! it will return true for stuff like 20a, a20, 20.a, 20a. and etc. it will return false for 20, 20.1 and any other number. It work in IE as far as I know.
Posted by :  Archive Import (Seth) at 16:25 on Tuesday, August 06, 2002
Hey anton thanks, this is exactly what I was looking for. I‹m glad I didn‹t use the function above :)
Posted by :  Archive Import (Nena) at 19:15 on Friday, August 23, 2002
Esta muy buena esa funcion esjusto lo que necesitaba
Posted by :  Archive Import (prtaft) at 19:05 on Wednesday, September 04, 2002
Anton is right on the money. Thanks.
Posted by :  Archive Import (Bala) at 05:14 on Friday, October 25, 2002
What about negetive numbers. isNAN wont return right results. This function by adding minus (-) in the list return true.

Great...
Posted by :  Archive Import (shaas) at 11:02 on Friday, November 01, 2002
What if the user enters multiple '.'?
Posted by :  Archive Import ($$) at 12:43 on Thursday, November 07, 2002
Just added negative value....

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

for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if ((i == 0) && (Char == "-")) // check first character for minus sign
continue;
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}
return IsNumber;

}

Didnt test it...please reply if u find any error....
By the way ... isNaN function does not apply when u need strict numeric validation.... for example:
'2a5' returns false (2 will be the numeric value) which should not be since the actual value intended was 25... the character 'a' accidentally typed.... get the point??
Posted by :  Archive Import (jscranton) at 16:35 on Tuesday, November 19, 2002
When I tried '2a5', I got true...
Posted by :  Archive Import (Fragus) at 10:02 on Tuesday, November 26, 2002
You don't need de IsNumeric variable, you can return true or false in the first instance when you got a no numeric character, this is the my change:

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var Char;


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

}

Posted by :  Archive Import (Bikash Biswas) at 02:39 on Saturday, November 30, 2002
There is a simple way to it.

Javascript has an inbuilt isNaN function to check numbers.

Please refer "http://developer.netscape.com/docs/manuals/js/core/jsguide15/fcns.html"
Posted by :  Archive Import (Krystan) at 09:22 on Monday, February 03, 2003
You should check for the empty string or you will assume the input is correct, this is clearly not right
Posted by :  Archive Import (John) at 17:42 on Tuesday, April 08, 2003
if (isNaN(form.field1.value)) {
alert('Please enter only numerical values into Field 1.');
}

Does the same thing!
Posted by :  Archive Import (Sengoku) at 13:07 on Thursday, April 10, 2003
You folks are using isNaN() incorrectly. You are getting the results you are seeing through pure serendipity. isNaN() is used to detect whether a number gets set to the value NaN (which is defined a 'not a number' - a designation similar to 'infinity', which isn't a number but defines something specific). In other words, check this site:

http://www.thedance.net/~roth/JAVASCRIPT/refp_268.htm
Posted by :  Archive Import (Greg) at 11:12 on Friday, April 18, 2003
Thanks John that was a good solution much easier then writing the whole Function out! This is what programming is about.
Posted by :  Archive Import (Younes) at 10:32 on Monday, May 26, 2003
I would change the code with Not a Number like this.

if (isNaN(pareseFloat(form.field1.value))) {
alert('Please enter only numerical values into Field 1.');
}

Use pareseInt if you don't need floating value

Posted by :  Archive Import (Younes) at 10:34 on Monday, May 26, 2003
You shall remove the 'e' from the word 'parese', because the form validation prohibits the word 'parese' without the e :s
Posted by :  Archive Import (Murali) at 08:30 on Friday, May 30, 2003
IsNumeric() did a good job for me
keep it up guys
Posted by :  Archive Import (Yuri) at 09:52 on Saturday, July 19, 2003
I have used the function above and it hang the entire IE. I would not recommend on using it. Use isNaN instead it works just fine.
Posted by :  Archive Import (Shane) at 02:02 on Monday, September 15, 2003
Yeah, I looked at that site and it said isNan() is used to check if something was a valid number. So i'll stick with isNaN(). Nice function though :).
Posted by :  grahamd at 10:31 on Wednesday, October 08, 2003
I'm looking for a function to validate a phone number. I was going to adapt the IsNumeric function to do this, but I can't get this to work at all even in the way it's written. I've copied it exactly using the validate function to call it. I'm I missing something?
Posted by :  spook at 01:27 on Monday, December 15, 2003
i can't believe all the odd ways i've read people try to sort this problem out!
Regular Expressions are the way to go when you need to check string contents.

myRegExp = /[0-9]+/g
myNumber = new String("93932")

if(myRegExp.test(myNumber))
{
there are numbers in myNumber
}
else
{
there are no numbers in myNumber
}

the cool thing about regular expressions is that you can do pattern matching too, not just a binary check for a condition.

ie. you could validate a phone number with the following patter:

myRegExpPhoneNumber = /(\d\d\d) \d\d\d-\d\d\d\d/

\d is a number 0 through to 9. So if you test (234) 983-8282 against it, it will return true, anything else will be false. Perfect. none of this isNan garbage.
Posted by :  fluoronaut at 08:17 on Wednesday, January 21, 2004
If you want to validate against a string containing only numbers, the expression is:

^-{0,1}\d*\.{0,1}\d+$

^ == beginning of line
-{0,1} == 0 or 1 minus signs
\d* == 0 or more digits
\.{0,1} == 0 or 1 decimal points
\d == 1 or more digits
$ == end of line
Posted by :  tbradner at 22:46 on Monday, March 07, 2005
You should never have multiple returns in any function!!!!!

Posted by :  colin.saxton at 06:04 on Monday, May 09, 2005
The last comment about multiple returns from function/method is BS!

if you have something like this

if(flag) {
Do some code...
} else {
showmessage;
}

looks better like this...


if(!flag) {
showmessage;
return;
}

do some code...

since it cuts down on the ammount of nessted code and its easier to read. It stems from machine code programming many moons ago when having more than one return statement really did send your head into overload!! In this day just use common sense!
Posted by :  norpel at 06:53 on Friday, May 13, 2005
the isNaN function does not work properly for this type of validation

the value 3a3 returns false (ie will not be picked up by the above validation functions using isNan)

i think reg expressions are the way to go for this
Posted by :  nskim at 00:24 on Monday, February 05, 2007
this regexp will check a integer number with commas or not

function checkInteger(obj) {

//regular expression should match number with commas or not
//1. ^-? <-- '-' is optional at the beginning
//2. \d{1,3} <-- with or without comma, first 3 digits
//3. \d{1,3}(\,\d{3})* <-- with comma, at least one digit with max of three before repeating like ',ddd'
//4. \d+ <-- without comma, match any number of integer(shouldn't be though)

re = /^-?(\d{1,3}|\d{1,3}(\,\d{3})*|\d*)$/g;

if ( ! re.test(obj.value) ) {

return false;

}

return true;
}
Posted by :  nskim at 03:01 on Monday, February 05, 2007
a better solution

//regular expression should match number with commas or not
//1. (^-? <-- '-' is optional at the beginning
//2. [1-9] <-- first digit should be between 1~9; 090 shouldn't be allowed
//3. (\d{1,2}(\,\d{3})* | <-- with comma, at least one digit with max of three before repeating like ',ddd'
//3. \d*) | <-- without comma, match any number of integer(shouldn't be though)
//4. ^0{1})$ <-- allow only one zero and no minus zero

re = /(^-?[1-9](\d{1,2}(\,\d{3})*|\d*)|^0{1})$/;
Posted by :  a1programmer at 11:51 on Wednesday, July 18, 2007
Or, you could keep it simple... ;)

function isNumeric(num){
if (num >=0 || num < 0)
return true;
return false;
}
Posted by :  sweet_namrata86 at 11:40 on Tuesday, January 08, 2008
Very good help for me.

Thanx guys..

keep it up.
Posted by :  jasan.aj at 01:31 on Friday, February 29, 2008
A little modification for avoiding multiple dots and Empty String:



function isNumber(sText) {
if (sText=="") return false;
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;
var dotCnt = 0;

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

}


To post comments you need to become a member. If you are already a member, please log in .

 



RELATED ARTICLES
Javascript - Enable and Disable form elements
by Jeff Anderson
This is a relatively little known and under-used feature of javascript which can be very useful in guiding a user through a form. Using the disabled tag, you can switch on and off elements in a form.
Javascript Onload Event
by Jeff Anderson
Sometimes you need to perform an action immediatley after the page has loaded. That's when the onLoad Event Handler comes in handy
Check IsNumeric Function
by Jeff Anderson
A javascript validation function to check whether the details entered by a user are numeric.
Form Validation Function
by Jeff Anderson
A javascript validation function that you can use to validate all types of forms.
JavaScript Field Is Empty Form Validation
by Jeff Anderson
This javascript function allows you to check whether a form field has been completed or not.
Check Email Validation Function
by Jeff Anderson
A javascript validation function to check whether the user has entered a valid email address in a form.
Javascript Get Selected Text
by Jeff Anderson
A cross-browser script to get text selected by the user
Multiple submit buttons on a single form
by Kiran Pai
This script shows you how to submit the contents of a form to different programs depending on which Submit button you press. Additionally it also shows how to call two different functions when you press the Submit button.
Validate Form and Disable Submit Button
by Marylou Marks
I have a form that validates info, but I also want to disable the submit button. The disable part worked before adding the form validating.
Simple date validation
by Chris Hogben
function that takes a date in three parts, day, month and year - returns true if it's a valid date.








Recent Forum Threads
• Re: Perl Script - File Handling.
• Open a file from website
• Re: to open 5 terminals from one and also execute different commands on each terminal
• read a selected multiple line, those should match some of the values read in the files..
• Help me please
• Empty the contents of a file.
• Month Start, End dates
• show hide problem in dynamic table creation
• Re: ASP Sendmail has huge delay - ANYONE??


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2008