473,325 Members | 2,805 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

JavaScript to check whether textbox contains only integer or numeric/number values

103 100+
Hi all,

I would like to get the Javascript code to check the textbox contains only numeric values or numbers..

I am using asp.net and c#.net..

Please help me..

Regards,
Mathew
Oct 18 '07 #1
23 138126
gits
5,390 Expert Mod 4TB
hi ...

you may use javascript built in isNaN() method for that ... it returns true in case it is NotaNumber else you get a false ...

kind regards
Oct 18 '07 #2
mathewgk80
103 100+
hi ...

you may use javascript built in isNaN() method for that ... it returns true in case it is NotaNumber else you get a false ...

kind regards
Hi Gits,

Can you please give an example for that???

regards,
Mathew
Oct 18 '07 #3
gits
5,390 Expert Mod 4TB
ok ... lets assume following example:

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.     <head>
  3.     <script type="text/javascript">
  4.         function check_field(id) {
  5.             var field = document.getElementById(id);
  6.  
  7.             if (isNaN(field.value)) {
  8.                 alert('not a number');
  9.             }
  10.         }
  11.     </script>
  12.     </head>
  13.     <body>
  14.     <form>
  15.         <input type="text" id="t_field"/>
  16.         <input type="button" value="check" onclick="check_field('t_field');"/>
  17.     </form>
  18.     </body>
  19. </html>
  20.  
kind regards
Oct 18 '07 #4
ananth
75
HI ,
The code above using NAN will not work properly try this.

Expand|Select|Wrap|Line Numbers
  1. function checkNum(x)
  2. {
  3.  
  4.   var s_len=x.value.length ;
  5.   var s_charcode = 0;
  6.     for (var s_i=0;s_i<s_len;s_i++)
  7.     {
  8.      s_charcode = x.value.charCodeAt(s_i);
  9.      if(!((s_charcode>=48 && s_charcode<=57)))
  10.       {
  11.          alert("Only Numeric Values Allowed");
  12.           x.value='';
  13.          x.focus();
  14.         return false;
  15.       }
  16.     }
  17.     return true;
  18. }
  19.  
  20.   <input type="text" id="t_field" onChange='checkNum(this)'/>
This will execute on the field exit or tabbing out of the field.

Hope this would be useful.
Oct 19 '07 #5
gits
5,390 Expert Mod 4TB
HI ,
The code above using NAN will not work properly try this.
nope ... it is working properly for the requirement. it checks for numeric values and it works! you didn't say why or what is not working properly!

your code should check for only Integers? you simply could use one line for that:

Expand|Select|Wrap|Line Numbers
  1. // in case value is an integer test_result will be true 
  2. // otherwise it will be false
  3. var test_result = /^\d+$/.test(value);
  4.  
kind regards
Oct 19 '07 #6
mathewgk80
103 100+
Hi all,

I would like to check whether the textbox contains only nmumberic values by using javascript...

Please help me...

Regards,
Mathew
Nov 8 '07 #7
iam_clint
1,208 Expert 1GB
I would use something similar to this and just call this function everytime you need to know if its numeric
Expand|Select|Wrap|Line Numbers
  1. <script>
  2. function isNumeric(val) {
  3.     var numeric = true;
  4.     var chars = "0123456789.-,+";
  5.     var len = val.length;
  6.     var char = "";
  7.     for (i=0; i<len; i++) { char = val.charAt(i); if (chars.indexOf(char)==-1) { numeric = false; } }
  8.     return numeric;
  9. }
  10. </script>
  11.  
so I would say if (isNumeric("whatever value here")) { alert("Its Numeric!!!"); }
Nov 8 '07 #8
acoder
16,027 Expert Mod 8TB
Or use regular expressions:
Expand|Select|Wrap|Line Numbers
  1. function isNumeric(str) {
  2.  return /^\d$/.match(str);
  3. }
Nov 9 '07 #9
iam_clint
1,208 Expert 1GB
Acoders way is better. Never even thought to do that :)
Nov 9 '07 #10
acoder
16,027 Expert Mod 8TB
Actually, there's a typo (or rather I missed a +):
Expand|Select|Wrap|Line Numbers
  1. function isNumeric(str) {
  2.  return /^\d+$/.match(str);
  3. }
Nov 9 '07 #11
acoder
16,027 Expert Mod 8TB
One more thing, this would only match positive integers, i.e. 0+.

If you want to match real numbers, you could try something like
Expand|Select|Wrap|Line Numbers
  1. /^(\+|-)?[1-9]\d*(\.\d*)?$/
Nov 9 '07 #12
nope ... it is working properly for the requirement. it checks for numeric values and it works! you didn't say why or what is not working properly!

your code should check for only Integers? you simply could use one line for that:

Expand|Select|Wrap|Line Numbers
  1. // in case value is an integer test_result will be true 
  2. // otherwise it will be false
  3. var test_result = /^\d+$/.test(value);
  4.  
kind regards

Hmmm... it's been a while since I've coded, but I'm unfamiliar with this syntax.

Unfortunately, I tried it and it didn't seem to work, whereas the previous (longer) solution did. This one-line code seemed to return a response of "false" even if a single integer was entered. (using IE 7.0.6)
Nov 12 '07 #13
Hi Mathew

Try this code. It Accepts only Numeric, u can modify it according to ur requirement.

Call the function onKeyPress event of textbox.

Expand|Select|Wrap|Line Numbers
  1.  function allownumber(e)
  2.    {
  3.  
  4.     var key = window.event ? e.keyCode : e.which;
  5.     var keychar = String.fromCharCode(key);
  6.     var reg = new RegExp("[0-9.]")
  7.     if (key == 8)
  8.     {
  9.      keychar = String.fromCharCode(key);
  10.  
  11.     }
  12.     if (key == 13)
  13.     {
  14.      key=8;
  15.      keychar = String.fromCharCode(key);     
  16.     }
  17.     return reg.test(keychar);
  18.    }
Thx

Hi all,

I would like to get the Javascript code to check the textbox contains only numeric values or numbers..

I am using asp.net and c#.net..

Please help me..

Regards,
Mathew
Nov 12 '07 #14
gits
5,390 Expert Mod 4TB
Hmmm... it's been a while since I've coded, but I'm unfamiliar with this syntax.

Unfortunately, I tried it and it didn't seem to work, whereas the previous (longer) solution did. This one-line code seemed to return a response of "false" even if a single integer was entered. (using IE 7.0.6)
it uses regEx to check the value ... i cannot test it in IE 7 due to having no IE but it should work ... how do you apply the check?

kind regards
Nov 12 '07 #15
Dasty
101 Expert 100+
Hmmm... it's been a while since I've coded, but I'm unfamiliar with this syntax.

Unfortunately, I tried it and it didn't seem to work, whereas the previous (longer) solution did. This one-line code seemed to return a response of "false" even if a single integer was entered. (using IE 7.0.6)
No, his regular expression check is right. It had to by some typo on your code that makes it to act incorrect. Try this:

Expand|Select|Wrap|Line Numbers
  1. <SCRIPT language=javascript>
  2. function checkNum(x)
  3. {
  4.   if (!(/^\d+$/.test(x.value)))
  5.   {
  6.     alert("Only Numeric Values Allowed");
  7.     x.focus();
  8.     return false;
  9.   }
  10.   return true;
  11. }
  12. </SCRIPT>
  13. <input type="text" id="t_field" onChange='checkNum(this)'/>
  14.  
I just put above advice into the code. As far as i know IE does not have any problems with regular expressions at all. But if you want to check something, you have to write clear what exact format of numbers do you want to validate. Do you want to allow negative / positive numbers? Do you want do check decimal numbers?
Nov 12 '07 #16
@mathewgk80
For allowing only numeric values to be placed inside a text box using JavaScript, we need to capture the “onKeyDown” event for the keyboard. This check is done on client side whenever a user enters a value in the textbox using keyboard keys.

Example of such a script is:

TextBoxTest.Attributes.Add(”onKeyDown”, “if((event.keyCode >= 48 && event.keyCode <= 57)||(event.keyCode >= 96 && event.keyCode <= 105)||(event.keyCode == 8 ) ||(event.keyCode == 9) || (event.keyCode == 12) || (event.keyCode == 27) || (event.keyCode == 37) || (event.keyCode == 39) || (event.keyCode == 46) ){return true;}else{return false;}”);

Regards,
Akshay Jain
Dec 13 '08 #17
acoder
16,027 Expert Mod 8TB
Akshay, welcome to Bytes and thanks for your contribution.

Unfortunately, the code you've posted is IE-specific and would not work cross-browser. In addition to that, this being the JavaScript forum, it's better to avoid .NET code and provide just the JavaScript.

Thanks.
Dec 13 '08 #18
yes you can use isNaN() function of javascript...
Dec 20 '11 #19
Expand|Select|Wrap|Line Numbers
  1. function chk(val)
  2. {
  3. var a=val.parseInt();
  4. if(a == a+1-1)//answer becomes true only if they are numbers
  5. {
  6. alert("its a number");
  7. }
  8. else
  9. {
  10. alert("not a number");
  11. }
Oct 15 '13 #20
acoder
16,027 Expert Mod 8TB
Have you tested your code to see if it works? It seems a very convoluted way to check for integers. See https://developer.mozilla.org/en-US/...jects/parseInt
Nov 28 '13 #21
Expand|Select|Wrap|Line Numbers
  1. function chk(val)
  2.     {
  3.     var a=parseInt(val);
  4.     if(a == a+1-1)//answer becomes true only if they are numbers
  5.     {
  6.     alert("its a number");
  7.     }
  8.     else
  9.     {
  10.     alert("not a number");
  11.     }
This works bro :)
Nov 29 '13 #22
Dormilich
8,658 Expert Mod 8TB
there is no need for the a+1-1 bit. if a were NaN (the only value parseInt() gives on failure), even then a==a would be false.
Dec 1 '13 #23
yes you are right @dormilich:)i'm new to programming and just now learning things..
Dec 2 '13 #24

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: ief | last post by:
hi all, i'm trying to check the length of a numeric value in a string. this is what i need to do: I have a string "Mystring (253)" and a string "SecondString (31548745754)" Now i have to...
2
by: Reddy | last post by:
Hi, How to check whether a given number is an integer Thanks, Reddy
6
by: Jan | last post by:
Hi, Is there any elegant way in VB.NET to check whether a certain string is part of a "collection" of strings. Something like IF "teststring" in {"string1", "string2", "string3",...
5
by: Eli | last post by:
Hi, I want to check whether a value is a scalar. A scalar can be: - None (null) - string - number (integer, float) - boolean How can I validate a value is one of these types? I care about...
13
by: nishit.gupta | last post by:
Is their any fuction available in C++ that can determine that a string contains a numeric value. The value cabn be in hex, int, float. i.e. "1256" , "123.566" , "0xffff" Thnx
19
Frinavale
by: Frinavale | last post by:
Filtering user input is extremely important for web programming. If input is left unfiltered users can input malicious code that can cripple your website. This article will explain how to make...
7
by: nussu | last post by:
Hi, Plz provide me javascript : javascript for a textbox to accept the values in decimals and within range i need to enter a value in textbox like 1.03 and it should be <3 (lessthan 3). Plz...
9
by: bizt | last post by:
Hi, I am using the following function to validate a forms value as an integer function isNumeric(str){ var numericExpression = /^+$/; if(str.match(numericExpression)){ return true; }else{
3
by: beary | last post by:
Hi, I have a number of text boxes for the user to input either numbers, or letters. Sometimes, the entry must be numeric. So I was thinking of using an onblur thing to check whether the value of...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.