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  ( 1361 ) (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: 183797 times Rating (91 votes): 
 3.6 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


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

 



RELATED ARTICLES
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
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.
Form Validation Function
by Jeff Anderson
A javascript validation function that you can use to validate all types of forms.
Check IsNumeric Function
by Jeff Anderson
A javascript validation function to check whether the details entered by a user are numeric.
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.
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.
Multiple submit buttons with form validation
by Paul Eckert
This code shows how to redirect a user to multiple sites, depending on which submit button he presses, but only after the form validates correctly.








Recent Forum Threads
• Access https in http page
• IE page Redirect
• Re: Javascript problem with document.write and accented characters
• Re: sorting and Linked list
• Re: need help linked list
• Re: Help with arrays
• Re: Reading from a file
• Re: Why Use Method?
• Re: Help with a simple program


Recent Articles
Multiple submit buttons with form validation
Understanding Hibernate ORM for Java/J2EE
HTTP screen-scraping and caching
a javascript calculator
A simple way to JTable
Java Native Interface (JNI)
Parsing Dynamic Layouts
MagicGrid
Caching With ASP.Net
Creating CSS Buttons


Site Survey
Help us serve you better. Take a five minute survey. Click here!

© Copyright codetoad.com 2001-2005