Any code of your own that you haven't looked at for six or more months might as well have been written by someone else. --Eagleson's Law
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:
Missouri Sycamores - 11/2011. Copyright © Steve Lautenschlager

How Can I Use Javascript to Allow Only Numbers to Be Entered in a TextBox?

By steve on January 11, 2007.
Updated on January 26, 2012.
Viewed 260,614 times (429 times today).
Article TypesLanguagesSoftware DevelopmentTechnologiesTechnologies
SnippetJavascriptClient sideHTMLWeb Browsers

Summary

Here I show how to use Javascript to allow only numbers to be entered in a textbox. This is useful for phone numbers, IDs, ZipCodes, and, well, that's about it.

This solution works in both IE and Netscape/Mozilla.

Try it here! Just type in the text box below. Note that digits are allowed and alphabetic characters are not allowed. Observe, too, that arrow keys and backspace are allowed so that you can still edit what you type.

Try It!

Example: Allow only numbers/digits in TextBox

<HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
</HTML>
Back to Top

User Comments (92)

Posted 2007 Jun 08 04:29 AM. reply
Thanks buddy.

birju shah
Replied 2007 Oct 18 06:10 AM by kejal. reply
<SCRIPT LANGUAGE="JAVASCRIPT"><!-- function check(contents) { if (((contents / contents) != 1) && (contents != 0)) {alert('Please enter only a number into this text box') } return false } //--></SCRIPT> <INPUT TYPE=TEXT SIZE=20 NAME="text1" onBlur="check(this.value)"> hello i also nedd a help from u.i want only characters from a to Z to use with this script.help me out and mail ur reply to kejal000@gmail.com
Replied 2010 Sep 27 06:34 AM by Muhammad Atiq (Pakistan). reply
<script language="javascript">
function IsNumeric(strString)
// check for valid numeric strings   
{
var strValidChars = "0123456789.-";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
return blnResult;
}
function frmvalidate(){

   if(document.frm.news_title.value==""){
      alert("Please enter ads fee");
      document.frm.news_title.focus();
      return false;
   }
   if (IsNumeric(document.frm.news_title.value) == false)
{
alert("Enter Integer value!");
    return false;
}
}

</script>
Replied 2011 Nov 14 01:25 AM by Ritesh. reply
Hello Bro, I have no idea about how to execute function written in Java-Script from HTML. So please reply me as early as possible. Currently I want that text field should accepts only numeric values and not more than 10 digits.
Replied 2012 Jan 12 08:32 AM by ft. reply
tf
Replied 2008 Nov 07 04:59 AM by govind. reply
one way to allow only numeric in textbox <input id='txtPerOwned"+ rowID +"' onkeypress ='return IsNumeric(event)' type='text' style='font-size:11Px' />" function IsNumeric(evt){ var keyCode = evt.which ? evt.which : evt.keyCode; if (keyCode == 46 || (keyCode >= 48 && keyCode <= 57)){ if (keyCode == 46){ var sCurrVal = $get(evt.srcElement.id).value if (sCurrVal.indexOf(".") > -1 ){ return false; } } return true; }else{ return false; } Enjoy!!!!!!!!!!!!!
Replied 2010 Sep 27 06:34 AM by Muhammad Atiq (Pakistan). reply
<<script language="javascript">
function IsNumeric(strString)
// check for valid numeric strings
{
var strValidChars = "0123456789.-";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
return blnResult;
}
function frmvalidate(){

if(document.frm.news_title.value==""){
alert("Please enter ads fee");
document.frm.news_title.focus();
return false;
}
if (IsNumeric(document.frm.news_title.value) == false)
{
alert("Enter Integer value!");
return false;
}
}

</script>
Replied 2012 Jan 03 22:36 PM by jamie. reply
Among hundreds of posts here and in other sites regarding all numeric input..and after like almost half a day of trying and searching...THIS is the ONLY one that makes a lot of sense.I wasted more than half a day with other's nonsense solution!...THANKS TO YOU...
Replied 2008 Nov 14 15:17 PM by Ahern. reply
How about i copy/paste characters ? Yes, It will let me, so this JavaScript is not bullet proof yet.
Replied 2010 Sep 27 06:33 AM by Muhammad Atiq (Pakistan). reply
<script language="javascript"> function IsNumeric(strString) // check for valid numeric strings { var strValidChars = "0123456789.-"; var strChar; var blnResult = true; if (strString.length == 0) return false; // test strString consists of valid characters listed above for (i = 0; i < strString.length && blnResult == true; i++) { strChar = strString.charAt(i); if (strValidChars.indexOf(strChar) == -1) { blnResult = false; } } return blnResult; } function frmvalidate(){ if(document.frm.news_title.value==""){ alert("Please enter ads fee"); document.frm.news_title.focus(); return false; } if (IsNumeric(document.frm.news_title.value) == false) { alert("Enter Integer value!"); return false; } }
Replied 2010 Oct 05 06:25 AM by kaarthik. reply
<HTML> <HEAD> <SCRIPT language=Javascript> <!-- function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } //--> </SCRIPT> </HEAD> <BODY> <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar"> </BODY> </HTML>
Replied 2011 Jan 19 19:28 PM by Jeyakumar. reply
Refer Here: http://jjeyakumar.blogspot.com/2011/01/key-in-only-numbers-in-text-box-using.html
Replied 2011 Nov 15 05:41 AM by vijay. reply
yes program is runing. no any allow charecter. thank you very much.
Replied 2012 Jan 04 05:20 AM by Rajesh. reply
It's fantastic. Thank u very much.
Replied 2012 Jan 20 01:04 AM by Munna. reply
he this eg. is not working
Posted 2007 Jun 13 11:34 AM. reply
Is there anyway to add the "-" key to the list of being included as well as only numbers?

I believe the keyCode for it is either 109 or 189. I have tried some nested if statements but nothing seems to work.

Jerod
Replied 2007 Jun 20 17:16 PM by Josef. reply
change the if statement to: if (charCode > 31 && ((charCode < 48 || charCode > 57) || charCode !=109)) return false;
Posted 2007 Jun 29 03:49 AM. reply
Thumbs up!!! Thank You

malfem
Posted 2007 Jul 23 21:50 PM. reply
LOVE IT!! TY!!!

JamRoll
Posted 2007 Jul 23 22:02 PM. reply
BETTER!

function isNum(char) {
if (char == 8) return true;
if (char == 9) return true;
if (char == 13) return true;
if (char == 35) return true;
if (char == 36) return true;
if (char == 46) return true;
if (char >= 48 && char <= 57) return true;
if (char > 111 && char <= 123) return true;
}

function checkNumber(evt, inputName) {
var charCode = (evt.which) ? evt.which : evt.keyCode
if (!isNum(charCode)) return false;

return true;
}

JamRoll
Replied 2007 Oct 29 14:17 PM by David C2. reply
The easiest way I found to allow dots and stuff (.-$, etc...)
would be to add this:
{..
var charCode = (evt.which) ? evt.which : event.keyCode

//.
if (charCode == 46) {
return true;
}

if (charCode > 31 && (charCode < 48 || charCode > 57))
..}

//If you want to check for whatever digit, just alert(charCode) and test it so you can see what code the key you just typed is... like this:
{..
var charCode = (evt.which) ? evt.which : event.keyCode

//.
alert(charCode); //this will display a message box with the code for the key you just typed

if (charCode > 31 && (charCode < 48 || charCode > 57))
..}
Posted 2007 Jul 25 01:05 AM. reply
Cheers!

Matt
Posted 2007 Sep 12 02:43 AM. reply
This function does not work if you type shift 4 or shift 9 etc.
Even alt gr with any number results in a text value

Dimmai
Replied 2007 Sep 16 13:34 PM by eboyjr. reply
Shift+4 and Shift+9 produce '$' and '(' those are not numbers
Replied 2009 Feb 26 03:49 AM by Anonymous. reply
This is not at all working
Posted 2007 Oct 02 11:34 AM. reply
but I can still copy then paste anything to the textbox (try mouse right click the choose Paste - since Ctrl-V is useless)
how to forbid it too?

moron
Posted 2007 Oct 12 20:20 PM. reply
You have one of them hidden feature bugs, event.keyCode will throw an error in non IE browsers. I believe this code should fix that. The 0 can be anything that would make it return true. I also removed the if statement, just to confuse everyone.

function intify(evt)
   {
   var charCode = evt.which ? evt.which : (window.event ? window.event.keyCode : 0);
   return (charCode <= 31 || (charCode >= 48 && charCode <= 57));
   }

chuck
Replied 2007 Oct 13 01:56 AM by chuck. reply
After looking at the code again I realized that the problem is not that event does not exist but rather that evt.which is sometimes 0, so the best code should be

...
var charCode = (evt.which != undefined) ? evt.which : evt.keyCode;
...
Posted 2007 Oct 25 04:36 AM. reply
<script type ="text/javascript" language ="javascript" >
function specialChars()
{
         var nbr;
         nbr=event.keyCode ;
         if ((nbr==45) || (nbr>=48 && nbr<=57)) {
         return true;
         }
         else
         {
         return false;
         }
      }
</script>
Call the function as below:
<asp:TextBox ID="TextBox1" runat="server" onkeypress="return specialChars();">
</asp:TextBox>

Satish
Posted 2007 Oct 25 04:38 AM. reply
function AllowOnlyNumeric()
{
         var nbr;
         nbr=event.keyCode ;
         if ((nbr==45) || (nbr>=48 && nbr<=57)) {
         return true;
         }
         else
         {
         return false;
         }
      }

Sri Amma Bhagawan
Posted 2007 Oct 25 06:38 AM. reply
Try with Firefox (I am using version 2.0.0.8 on Windows (en), finnish keyboard): switch Numlock off and press numpad-5 (or any other numeric key on the numpad) and you get a javascript error "event is not defined". See line
var charCode = (evt.which) ? evt.which : event.keyCode

there somehow Firefox gives
evt.which
an undefined value, and tries thus evaluate the code
event.keyCode
, which looks like a typo....

Btw, anyone noticed before that Firefox gives different event.which/event.keyCode values for same key depending on the event handler called: onkeydown and onkeyup vs. onkeypress? Like in this case only onkeypress gets the undefined value with from numpad numlock off.

Tuomas
Replied 2007 Oct 25 06:51 AM by Tuomas. reply
...evaluate the code
event.keyCode
, which looks like a typo....

I mean it most probably should be "evt.keyCode", not "event.keyCode".
Posted 2007 Oct 26 11:13 AM. reply
How come i copy and paste the codes but i still can key in characters?
I thought just for numbers only

Alex
Replied 2007 Oct 26 22:02 PM by Steve. reply
Hi Alex, The script works above on this page. Only numbers will show up in the text box.
Posted 2007 Oct 31 10:34 AM. reply
You can still paste characters ;)

przylepa.pl
Replied 2007 Oct 31 19:55 PM by Steve. reply
Good point!
Posted 2007 Nov 27 20:05 PM. reply
can't work if you copy and paste number like this 1$.

.net
Replied 2007 Nov 27 20:43 PM by sony. reply
Hi .Net, IE --> Can't work Mozila --> Can work any idea? Thanks
Posted 2007 Dec 28 06:13 AM. reply
Doesn't work in IE7

Jason
Replied 2008 Jan 27 08:29 AM by Roy. reply

    function onlyNumbers(e,txt){

        var keynum;
        var keychar;
        var numcheck;

        if(window.event){ // IE
            keynum = e.keyCode;
        }else if(e.which){ // Netscape / Firefox / Opera
            keynum = e.which;
        }
        
        keychar = String.fromCharCode(keynum);
        numcheck = /\d/;
        
        return numcheck.test(keychar) || "abcdefghin\b\t¼¾".indexOf(keychar) != -1;
    
    }
Replied 2008 Feb 13 01:00 AM by Anonymous. reply

<script type="text/javascript">

function CheckKeyCode()
{
  if( (event.keyCode == 189 || event.keyCode == 109) ||
      (event.keyCode >= 48 && event.keyCode <= 57) || 
      (event.keyCode >= 96 && event.keyCode <= 105) ) {
    return true; }
  else {
    return false;
  }
}
</script>

Zip Code: <input type="text" onkeydown="return CheckKeyCode()"/>
Posted 2008 Apr 25 08:52 AM. reply
Tkz Man!!

Master code.

Tibox
Posted 2008 May 14 15:06 PM. reply
Oh Dude....Thanks a ton buddy...

Sudhakar Janne
Posted 2008 Aug 03 17:37 PM. reply
Thanks, man!
Works perfectly!

JP
Posted 2008 Aug 07 09:48 AM. reply
Great code! I modified it slightly to allow the key codes to be listed as an array. Simplifies it quite a bit

//Convert array into object
function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

//Allow only numeric input, decimal point, backspace
function isNumberKey(evt)
{
	var myValidChars = new Array(0,8,46,48,49,50,51,52,53,54,55,56,57);
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode in oc(myValidChars))
	return true;
	return false;
}

Robert
Replied 2009 May 05 05:37 AM by Denny. reply
Thankz for the script

but one problem
this script will allow you to enter values like
23.32.36..35
or
..............
or
0....................1
etc
Posted 2008 Aug 12 02:20 AM. reply
Beautiful script... Keep up the good work

Admir
Posted 2008 Aug 14 06:08 AM. reply
Good work. It helped me.

Rose
Posted 2008 Aug 18 22:59 PM. reply
THANKS A LOTS

Katsuke
Replied 2009 Apr 24 03:25 AM by kishore. reply
use isNaN(value)
Posted 2008 Oct 21 01:53 AM. reply
Good, it works perfectly keep up this good job

Aarthi
Replied 2008 Dec 17 03:48 AM by anilreddy. reply

function numbersonly()
	{
		if(!((event.keyCode>=48)&&(event.keyCode<=57)))
		{
		event.keyCode=0;
		} 
				
               }
if u have any doubts send itsmeanilreddy@rediffmail.com
Posted 2008 Nov 14 15:18 PM. reply
This JavaScript is not bullet proof. You could copy/paste anything on the text box and it will accept it.

AHern
Posted 2008 Dec 16 04:21 AM. reply
thats really a nice code and helped me to fix the problem..

Surbhi
Replied 2008 Dec 17 03:46 AM by anilreddy. reply
function numbersonly() { if(!((event.keyCode>=48)&&(event.keyCode<=57))) { event.keyCode=0; } } if u have any doubts send itsmeanilreddy@rediffmail.com
Replied 2008 Dec 17 06:25 AM by Hemant. reply
thanks all for the info to enter only numbers,but how to restrict numbers in the a particular range say 1-10??
Posted 2008 Dec 18 01:15 AM. reply
how can i check the emailid expression by using javascript?

thanku

swetha
Posted 2009 Jun 30 09:53 AM. reply
how to create float type validations in javascript

samy
Replied 2009 Jun 30 10:08 AM by samy. reply
longitude(textbox) should be entered float type
Posted 2009 Nov 04 08:42 AM. reply
The Script given above works wonders and is too good. Just to add some thing as a Users Prospective we can give a alert message to the user stating that the numbers are only allowed. the function can be like-
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
{alert("Only numbers are allowed allowed.");
return false;}

return true;
}

Nilay
Posted 2009 Nov 13 04:57 AM. reply

function AllowNumericOnly(e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (event) keycode = event.keyCode;
else if (e) keycode = e.which;
else  return true;
if( (keycode > 47 && keycode <= 57) )
{
return true;
}
else {
return false;
}
return true;
}
You can call this function on page_load event like this
txtPhoneno.Attributes.Add("onkeypress", "return AllowNumericOnly(e);")
and your textbox should be...

<asp:TextBox ID="TextBox1" runat="server" onkeypress="return AllowNumericOnly(this);"></asp:TextBox>


Rajesh Bhimani [SURAT]
Posted 2009 Nov 16 15:12 PM. reply
is there a way to apply this function to a certain cell created in javascript e.g. applying it to :
var cell3 = row.insertCell(2);
      var element2 = document.createElement("input");
      element2.type = "text";
      cell3.appendChild(element2);
?

vivin patel
Posted 2009 Dec 08 00:23 AM. reply
thanks For Nice code

Ramakant
Posted 2009 Dec 21 14:41 PM. reply
Thanks, It works !!!!!!!

kiran
Posted 2010 Apr 06 07:43 AM. reply
numbersonly is gud.. Thanks..

numbersonly
Posted 2010 Apr 08 04:01 AM. reply
Thanx Friend,
It helped me a lot..

Kishore
Posted 2010 Jun 21 02:42 AM. reply
Dear Sir,

Thank you for such a nice script
Kashif

kashif Usman
Posted 2010 Jun 23 05:20 AM. reply
Hi,

This one is not working in IE6. Do you have any solution . Kindly help me.

Atheeq
Posted 2010 Jun 23 23:32 PM. reply
"textbox allows only a valid mobile number means it should allow up to 10 digits and it should not allow all are 0's" how could i go through this

suseela
Posted 2010 Sep 08 16:02 PM. reply
Thanks a lot, that worked like a charm and is SUPER effective! Awesome!

Filipe
Replied 2010 Sep 21 21:54 PM by palani. reply
//Number Validation function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; else return true; } <asp:TextBox ID="txtSkills" runat="server" onkeypress="return isNumberKeyevent);"></asp:TextBox>
Posted 2010 Oct 21 21:49 PM. reply
Great work!

Robert Green
Posted 2011 Mar 03 12:53 PM. reply
This solution is flawed. Copy any text and paste into textbox.

Tito
Replied 2011 Mar 24 09:55 AM by Phil E Stein. reply
Yup - very flawed! Firstly you can paste *anything* using a right-click of the mouse. Secondly it will not allow numbers on the numeric keypad. Thirdly it will not allow a tab character. Fourthly it will not allow a user to move cursor with arrow keys. Shall I continue? Fifthly it will not allow to delete using backspace. Sixthly it will not allow to delete using delete key. More? Is it currency? Need a decimal point? If so they're different on alpha / numeric keyboard. You should probably check out using regular expressions such as: function IsNumeric(str){ return ValidateInput(/^\d+$/,str); } function IsFloat(str){ return ValidateInput(/^\d*\.?\d{1,2}$/,str) } Even then, you might want to ensure you get rid of whitespace using \s* I'm a complete newbie to JS but I've been having some fun with regexes and keyCodes.
Replied 2011 Mar 24 10:03 AM by Phil Er Up Guv. reply
Oops - I'll correct myself, it DOES allow backspace and tab, but I'm a tad shocked it completely misses the numeric keypad when its trying to filter in just numbers.
Posted 2011 Mar 10 04:43 AM. reply
Thank you for the quick solution... I like it.. easy to understand... it took only 2 mins to implement it.... :)

thanks you

Saqib Designs
Posted 2011 Jul 22 02:28 AM. reply
Hi Steve,

Copy & Paste allows all alphabets and special characters in the above textbox.
Pls Check.

Kingsley
Posted 2011 Sep 15 07:09 AM. reply
Hi,
I tried this code .working fine in firefox but not not working in ie.not able to figure out the problem.please help me in fixing this issue.

sowmya
Posted 2011 Oct 02 22:59 PM. reply
Write a GUI program in java that will list down all numbers entered on a textbox using a list component.

Gwapo
Posted 2011 Nov 04 08:02 AM. reply
Hey Its Really Working!!! I thank You So Much!!! I am Very Happy!!!

Sesuraj
Posted 2011 Nov 06 00:20 AM. reply
good thanks. worked.

mohamad
Posted 2011 Nov 11 14:18 PM. reply
10000000000000 thanks! Simple and elegant that even I can apply it! Thanks!

Valeka
Posted 2011 Nov 17 08:58 AM. reply
gooooooooooo
Posted 2011 Dec 21 08:18 AM. reply
Hi, Nice post. I added the below line of code
alert("pls enter digits only.");
in if block. Keep going on like this useful posts STEVE.....

MuraliKrishna
Replied 2012 Jan 13 13:10 PM by Sherry. reply
Steve's original code works well for the form against which I am applying it. However, I would like to pop up an alert message. When I try to apply an alert, the alert pops up just fine but then the person cannot return to entering numbers. Almost as if the box is "locked" from entries after the alert pops up. Any thoughts? Here is the code I am using:
 
function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode;
         if (charCode > 31 && (charCode < 48 || charCode > 57))
		 (alert("Only numbers allowed."))
            return false;

		return true;
      }
and then in the entry field section I use:

onkeypress="return isNumberKey(event)">
Posted 2011 Dec 21 08:19 AM. reply
HI
NICE POST

MuraliKrishna
Posted 2012 Jan 07 01:46 AM. reply
function validation() { var alphaexp=/^[0-9]+$/; if(form1.Text1.value.length != 0) { if(form1.Text1.value.match(alphaexp)) { return true; } else { alert("enter number only"); form1.Text1.value = ""; return false; } } } hai everyone plz run this code and see, it too validating the requirement but allow starting letter I wanna know why....?

vinoth
Posted 2012 Jan 17 03:47 AM. reply
May Be U R calling this function in wrong event...You shouled call it into keypress event of textbox

mohini
Posted 2012 Jan 18 23:51 PM. reply
aasp.vb* pages textbox content data only number typing string, char look

chandrakumar
Posted 2012 Jan 30 07:39 AM. reply
I have textbox inside gridview. need to validate this textbox for numeric values.i tried using above code but its giveng me object required error.my code is as shown below. <asp:TextBox ID="txt1" runat="server" MaxLength="4" Text='<%# Eval("value") %>' OnKeyPress=" return AllowNumericOnly(this);"> javascirpt used is function AllowNumericOnly(e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (event) keycode = event.keyCode; else if (e) keycode = e.which; else return true; if ((keycode > 47 && keycode <= 57)) { return true; } else { return false; } return true; } i need to support this functionality in Mozilla and IE. can anyone help me

Akshata
Posted 2012 Feb 02 19:04 PM. reply
But I can do copy some text and paste to the textbox. Its allowing. Any idea how to avoid this?

Prabu
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.