|
|
Home » Javascript » Article
Javascript IsNumeric Function
|
| Article by: | Jeff Anderson ( 1362 ) (2/26/2002) |
|
| Summary: | A javascript validation function to check whether the details entered by a user are numeric. |
|
| Viewed: 1038903 times |
Rating (189 votes): |
|
3.5 out of 5 |
|
|
|
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.
|
|
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. Im glad I didnt 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 (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 (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;
}
| |
Posted by :
partha at 12:47 on Monday, March 02, 2009
|
For signed number I found the below link helpful:
http://shawpnendu.blogspot.com/2009/03/cross-browser-javascript-isnumeric.html
| |
Posted by :
Skews Me at 17:55 on Saturday, March 21, 2009
|
Neither of nskim's examples work:
re = /^-?(\d{1,3}|\d{1,3}(\,\d{3})*|\d*)$/g;
re = /(^-?[1-9](\d{1,2}(\,\d{3})*|\d*)|^0{1})$/;
I've tested using "1,000", "10,000", and "100,000" and get different, incorrect results.
| |
Posted by :
nataxia at 15:16 on Friday, September 18, 2009
|
f(n) {
return n && n.constructor === Number;
}
<Added>
(if strictly typing argument)
| |
Posted by :
a1programmer at 12:28 on Thursday, February 18, 2010
|
function isNumeric(num){
... return (num >=0 || num < 0);
}
| |
Posted by :
joe5555 at 08:13 on Friday, March 05, 2010
|
I know this is ancient, but still ...
According to your function:
5.5.52 IS NUMERIC
1e4 IS NOT NUMERIC
-6.5 IS NOT NUMERIC
1.23E+11 IS NOT NUMERIC
These are all incorrect responses.
Ouch? You should either take this stuff down or at least make it function properly. Scientific notation should pass an is_numeric function. All these return correctly from, for example, PHP's is_numeric.
| |
Posted by :
didihh at 10:21 on Sunday, May 30, 2010
|
Hello,
M
How are you doing? Hope you are alright.
Last week, I bought Many items.
it is very cheap and I get it in 5 days. The quality is very good.
The site also sell Sneakers, handbag, purse, jeans, sunglass, hat and so on.
I never forget to share good things with friends.
So,if you are interested in it, you can have a look.
I think you will get some surprise.
This is their : www.newgoing.com
| |
Posted by :
wholesalegoods at 11:04 on Tuesday, July 05, 2011
|
welcome to our website:
------- http://www.tradetrusting.com --------
if you like to order anything you like.
More details,
please just browse our website Quality is our Dignity;
Service is our Lift.
enjoy yourself.
thank you!!
------- http://www.tradetrusting.com -----
| |
Posted by :
kaikaiee at 22:20 on Wednesday, July 06, 2011
|
welcome to our websit:...
╭══════════════╮
..... http://www.voguecatch.us ...
╰══════════════╯
Wow! This site:
Both cheaper and fashion, and good products.
Purchase will have small gift to send.
http://www.voguecatch.us was a good site.
Like this discovery.
... http://www.voguecatch.us ......
***★Nike☆jordan s-h-o-e-s $30--35★***
****☆ Best online store ☆****
******(U-G-G)*******
... http://www.voguecatch.us .....
....Welcome you to visit thanks..
| |
Posted by :
sasfguysaf at 09:30 on Friday, July 08, 2011
|
very good web: === http://www.bingstore.us
The website wholesale for many kinds of fashion shoes, like the nike, jordan, prada, also including the jeans, shirts, bags, hat and the decorations.
All the products are free shipping, and the the price is competitive, and also can accept the paypal payment., After the payment, can ship within short time.
We will give you a discount
WE ACCEPT PYAPAL PAYMENT
YOU MUST NOT MISS IT!!!
=== http://www.bingstore.us
thank you!!!
Believe you will love it.
We have good reputation, fashion products,
come here quickly== http://www.bingstore.us
Opportunity knocks but once
| |
Posted by :
tolon at 09:13 on Thursday, July 28, 2011
|
Wonderful.
Share a website with you ,
put this url in google sirch
( http://www.yessoso.com/ )
Believe you will love it.
We accept any form of payment.
werwer
| |
Posted by :
meimeikk at 07:31 on Wednesday, August 03, 2011
|
Hello, everybody, the good shoping place, the new season approaching, click in.
Welcome to http://www.proxy4biz.com
Air Jordan (1-24) shoes $35
UGG BOOT $50
Nike shox (R4, NZ, OZ, TL1, TL2, TL3) $35
Handbags ( Coach Lv fendi D&G) $35
T-shirts (polo, ed hardy, lacoste) $16
Jean (True Religion, ed hardy, coogi)$34
Sunglasses ( Oakey, coach, Gucci, Armaini)$15
New era cap $16
Bikini (Ed hardy, polo) $18
FREE SHIPPING
http://www.proxy4biz.com
http://www.proxy4biz.com
http://www.proxy4biz.com
http://www.proxy4biz.com
http://www.proxy4biz.com
http://www.proxy4biz.com
| |
Posted by :
j298719302 at 08:40 on Monday, August 08, 2011
|
http://www.goelectronstore.com
Apple mac books: 280- 520 USD
Iphone 4: 260 USD
Ipad 2 64gb wifi 3G : 330 USD
New Ipod touch 64gb: 120 USD
Dell Alienware M17x: 700 USD
Dell Alienware M15x: 500 USD
MacBook Pro MC024 LL/A 17-inch 2.66GHz Intel Core i7: 510 USD
MacBook Pro MC373 LL/A15.4-inch 2.66GHz Intel Core i7: 485 USD
BlackBerry Pearl 3G 9105: 350 USD
Nikon F 6 SLR camera - 35mm: 685 USD
Nikon D3000 (with 18mm-55mm and 55mm-200mm lens): 315 USD
Nikon D3X : 985 USD
Canon EOS 5D Mark: 565 USD
Playstation 3 PS3 Metal Gear Solid 4 80GB Bund: 220 USD
Free shipping , P A Y P A L accepted! Fast and door to door delivery! If necessary, please
http://www.goelectronstore.com
| |
Posted by :
ghyuguytg at 07:44 on Monday, August 22, 2011
|
Hello,
Send Christmas Gifts. Buy more to send. On this site==== http://www.goodshopping.us/ ,
good place for shopping, fashion, sexy, personality, maturity, from here to begin. Are you ready?
Air jordan(1-24)shoes $30
Handbags(Coach l v f e n d i d&g) $35
Tshirts (Polo ,ed hardy,lacoste) $15
Jean(True Religion,ed hardy,coogi) $30
Sunglasses(Oakey,coach,gucci,A r m a i n i) $15
New era cap $10
accept paypal or credit card and free shipping
====== http://www.goodshopping.us/ ====
| |
|
|
|
|
Posted by :
zhmmii at 09:05 on Sunday, October 16, 2011
|
Hello, everybody, the good shoping place, the new season approaching, click in.
Welcome to http://www.top4biz.com
Air Jordan (1-24) shoes $35
UGG BOOT $50
Nike shox (R4, NZ, OZ, TL1, TL2, TL3) $35
Handbags ( Coach Lv fendi D&G) $35
T-shirts (polo, ed hardy, lacoste) $16
Jean (True Religion, ed hardy, coogi)$34
Sunglasses ( Oakey, coach, Gucci, Armaini)$15
New era cap $16
Bikini (Ed hardy, polo) $18
FREE SHIPPING
=== http://www.top4biz.com
===http://www.top4biz.com
=== http://www.top4biz.com
===http://www.top4biz.com
=== http://www.top4biz.com
===http://www.top4biz.com
=== http://www.top4biz.com
===http://www.top4biz.com
=== http://www.top4biz.com
=== http://www.top4biz.com
===(http://www.top4biz.com
| |
|
|
Posted by :
kristhellde at 20:13 on Monday, October 24, 2011
|
welcome to our website:
------- http://www.chic-goods.com/ --------
if you like to order anything you like.
More details,
please just browse our website Quality is our Dignity;
Service is our Lift.
enjoy yourself.
thank you!!
------- http://www.chic-goods.com/ -----
| |
Posted by :
jordan high heels at 03:12 on Wednesday, October 26, 2011
|
Our crazy sales promotion, global the lowest price, welcome to patronize!
| |
Posted by :
zhangq at 08:53 on Sunday, October 30, 2011
|
Hello, everybody, the good shoping place, the new season approaching, click in.
Welcome to http://www.luckygrip.com
Air Jordan (1-24) shoes $35
UGG BOOT $50
Nike shox (R4, NZ, OZ, TL1, TL2, TL3) $35
Handbags ( Coach Lv fendi D&G) $35
T-shirts (polo, ed hardy, lacoste) $16
Jean (True Religion, ed hardy, coogi)$34
Sunglasses ( Oakey, coach, Gucci, Armaini)$15
New era cap $16
Bikini (Ed hardy, polo) $18
FREE SHIPPING
http://www.luckygrip.com
http://www.luckygrip.com
http://www.luckygrip.com
http://www.luckygrip.com
http://www.luckygrip.com
http://www.luckygrip.com
| |
Posted by :
ptddd at 19:59 on Sunday, November 20, 2011
|
Whereas the most recent winter Moncler Online Store for females or males have abruptly come into trend, gentlemen were in no way deprived of looking at Moncler Mens Coats go out of trend. In reality, men’s suits likewise have gone through great modification specifically in their models. Apart from Moncler Women Jackets, modern day fabric can now be adaptable in various New Moncler Down Jackets, which inturn permits tailors to make up special models. Discount Moncler Mens are the years where exactly the jaded dark-colored suit was the greatest in men’s vogue http://www.monclermenstore.com/.
| |
Posted by :
zzxxmm at 09:22 on Tuesday, November 22, 2011
|
Tell you a big news!
====== http://www.cc2biz.com ======
Wholesale(Or Retail) cheap Ugg,Jerseys,Nike, air Jordan fusion, bbc, Evisu, crocodile, ed hardy, polo, t-shirt, lacoste, bape, louis vuitton, chanel, handbag, fendi, Versace, GUCCI, lv, Ladies, Handbags, DB, MIUMIU.etc.
====== http://www.cc2biz.com ======
Air max,Shox,Tn,Dunk,AF1 (1-24)shoes $35
Handbags(Coach l v f e n d i d&g) $35
Tshirts (Polo ,ed hardy,lacoste) $15
Jean(True Religion,ed hardy,coogi) $30
Sunglasses(Oakey,coach,gucci,A r m a i n i) $15
New era cap $12
Bikini (Ed hardy,polo) $20
Accept Credit card
Business with this site now,You can earn more money and enjoy your shopping life
====== http://www.cc2biz.com ======
| |
Posted by :
jioe556 at 01:23 on Monday, December 12, 2011
|
Anton, thank you, glad to get your help.
http://www.monclerdoudoune7femme.com
| |
Posted by :
jioe556 at 01:24 on Monday, December 12, 2011
|
Anton, thank you, glad to get your help.
<BR><BR><B><Added></b><BR><BR><A HREF="http://www.monclerdoudoune7femme.com/" target=_blank>http://www.monclerdoudoune7femme.com/</A><br>
| |
Posted by :
erttrtrty at 06:44 on Monday, December 19, 2011
|
Hello, everybody, the good shoping place, the new season approaching, click in. Welcome to ==== www.surprisefirms.com ==
Air Jordan (1-24) shoes $35
UGG BOOT $50
Nike shox (R4, NZ, OZ, TL1, TL2, TL3) $35
Handbags ( Coach Lv fendi D&G) $35
T-shirts (polo, ed hardy, lacoste) $16
Jean (True Religion, ed hardy, coogi)$34
Sunglasses ( Oakey, coach, Gucci, Armaini)$15
New era cap $16
Bikini (Ed hardy, polo) $18 .
=== http://www.surprisefirms.com
=== http://www.surprisefirms.com
=== http://www.surprisefirms.com
| |
Posted by :
codetutorial at 10:40 on Monday, December 26, 2011
|
In general it will discuss the construction of the connection strings and schema.ini files needed to bind to a delimited text file and it will define an approach for editing and saving delimited text files.
http://codetutorial.net/c/c-custom-controls/how-to-using-delimited-text-files-in-c.html
| |
|
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. |
 |
Check IsNumeric Function by Jeff Anderson
A javascript validation function to check whether the details entered by a user are numeric. |
 |
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 Get Selected Text by Jeff Anderson
A cross-browser script to get text selected by the user |
 |
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 onUnload Event Handler by Jeff Anderson
The onUnload Event Handler allows you to perform an action as the user leaves the page. |
 |
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. |
 |
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. |
 |
| |