In my form I want to allow typing of integer values only in a textbox. How to do that?
-
http://stackoverflow.com/questions/828309/textbox-allow-only-letters – Uwe Keim Mar 16 '12 at 05:38
19 Answers
You can use RegularExpressionValidator for this. below is the sample code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="TextBox1" runat="server"
ErrorMessage="Only Numbers allowed"
ValidationExpression="\d+">
</asp:RegularExpressionValidator>
above TextBox only allowed integer to be entered because in RegularExpressionValidator has field called ValidationExpression, which validate the TextBox. However, you can modify as per your requirement.
You can see more example in MVC and Jquery here.

- 999
- 8
- 22

- 7,477
- 6
- 36
- 56
-
3Note that it still lets you type non-numbers. But if you do, a red validation message shows up and postback buttons do not submit. – Curtis Yallop Jun 24 '14 at 20:50
-
Note that when the validation message is hidden, it uses "visibility: hidden" rather than "display: none" on the validation message span which causes an empty space to show up when the validation message is not displayed. – Curtis Yallop Jun 24 '14 at 20:50
-
@CurtisYallop this is true when Validator.display = "Static", to avoid it use Validator.display = "Dynamic" – Hidalgo Jul 08 '14 at 09:13
-
1it's better way to solve this problem is use javascript , described in below answer, tanx to @madhu – R.Akhlaghi Feb 10 '15 at 06:13
-
Can I also use the same method to only allow up to 5 numbers and not more? – SearchForKnowledge Apr 13 '15 at 17:50
<HTML>
<HEAD>
<SCRIPT language=Javascript>
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.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>

- 2,205
- 16
- 16
-
12This is a much better solution than the accepted answer. Not allowing your user to input non-digits is much more convenient for the user than letting them and telling them they're wrong afterwards. Also, when the post-back situation gets a little complicated much easier to do the logic client side. – Rudi Kershaw Nov 24 '14 at 10:14
-
@RudiKershaw - Is it possible to enter only numbers & minus sign in a textbox? – Learner Jun 01 '15 at 10:49
-
Worked like a charm, thanks. @Learner just add console.log(charCode); to see the code of specific characters like this: `function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : evt.keyCode; console.log(charCode); return (charCode > 31 && (charCode < 48 || charCode > 57) ? false : true); }` – cjohansson Aug 28 '17 at 12:26
-
-
Nice solution, just one thought. Isn't `(charCode > 31 && charCode < 48) || charCode > 57` more readable? – obl Sep 19 '18 at 20:56
-
2
-
This approach seems to be near-perfect. However, it doesn't work when non-numeric values are pasted from the clipboard. Seems like the best option is RegEx validation on client side as well as server side. – priyamtheone Jun 13 '20 at 16:59
Try this:
Note:This is using Ajax Toolkit
First add Ajax Script Manager and use the below Code
<asp:FilteredTextBoxExtender ID="TextBox1_FilteredTextBoxExtender" runat="server"
Enabled="True" TargetControlID="TextBox1" FilterType="Numbers">
</asp:FilteredTextBoxExtender>

- 4,672
- 4
- 19
- 26
Easy Method:-
You can use the onkeydown Property of the TextBox for limiting its value to numbers only..
Very easy..:-)
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);"></asp:TextBox>
!(keyCode>=65) check is for excludng the Albphabets..
keyCode!=32 check is for excluding the Space character inbetween the numbers..

- 399
- 3
- 8
-
1Almost perfect :-) It also accepts all characters you can type with numeric keys at the top of main keyboard like "@" or "čšťľ" etc. I did it like this: return (!((event.keyCode>=65 && event.keyCode <= 95) || event.keyCode >= 106 || (event.keyCode >= 48 && event.keyCode <= 57 && isNaN(event.key))) && event.keyCode!=32); – a.farkas2508 Feb 06 '18 at 11:16
-
An even easier method is to use the TextMode
attribute:
<asp:TextBox runat="server" ID="txtTextBox" TextMode="Number">

- 17,750
- 17
- 113
- 128
-
-
@IbraHimM.Nada https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.textmode(v=vs.110).aspx – A-Sharabiani Jul 11 '18 at 12:48
-
-
1The intelliSense in Visual Studio said "Number" didn't exist as an option. Well I tried it anyway since the MSDN doc @A-Sharabiani listed had it there. It worked perfectly. Thanks so much! – My Stack Overfloweth Jun 03 '20 at 14:56
-
1Intellisense shows "Number" as an option for me (using VS2017 .NET4.7.2), making this the simplest and best solution, for me at least :) – Zeek2 Feb 17 '21 at 16:24
-
1But, for me, it also shows up & down arrows at the RHS (in FireFox browser), which I do not want, sigh :( – Zeek2 Feb 17 '21 at 16:30
-
1This is the best and least convoluted answer IMHO. Direct on the textbox element and you can enter currency (Numbers and Period). I'm an MVC guy who's getting use to ASP.NET controls so a great big thank you! – PhillipPDX Aug 24 '23 at 17:19
try this instead
Note:This is using Ajax Toolkit
First add Ajax Script Manager and use the below Code to apply filter to the textbox
Provide the Namespace at the beginning of the asp.net page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:TextBox ID="TxtBox" runat="server"></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" Enabled="True" TargetControlID="TxtBox" FilterType="Numbers" FilterMode="ValidChars">
</cc1:FilteredTextBoxExtender>

- 13,316
- 6
- 32
- 53

- 81
- 1
- 4
step by step
given you have a textbox as following,
<asp:TextBox ID="TextBox13" runat="server"
onkeypress="return functionx(event)" >
</asp:TextBox>
you create a JavaScript function like this:
<script type = "text/javascript">
function functionx(evt)
{
if (evt.charCode > 31 && (evt.charCode < 48 || evt.charCode > 57))
{
alert("Allow Only Numbers");
return false;
}
}
</script>
the first part of the if-statement excludes the ASCII control chars, the or statements exclued anything, that is not a number
Another solution is to use a RangeValidator where you set Type="Integer"
like this:
<asp:RangeValidator runat="server"
id="valrNumberOfPreviousOwners"
ControlToValidate="txtNumberOfPreviousOwners"
Type="Integer"
MinimumValue="0"
MaximumValue="999"
CssClass="input-error"
ErrorMessage="Please enter a positive integer."
Display="Dynamic">
</asp:RangeValidator>
You can set reasonable values for the MinimumValue
and MaximumValue
attributes too.

- 19,223
- 13
- 68
- 84
It can be done with a compare validator as below. Unlike the other answers, this also allows negative numbers to be entered, which is valid for integer values.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ControlToValidate="TextBox1" runat="server" ErrorMessage="Integers only please" Operator="DataTypeCheck" Type="Integer" ></asp:CompareValidator>

- 2,179
- 22
- 32
Just use
<input type="number" id="foo" runat="server" />
It'll work on all modern browsers except IE +10. Here is a full list:

- 3,365
- 1
- 35
- 41
-
Please add details about which browsers / html versions for which this will work. – Edward Apr 02 '15 at 20:26
-
It shows error `Parser Error Message: 'number' is not a valid type for an input tag.` – maspai Oct 08 '20 at 04:44
Try This :
<input type="text" onkeypress = "return isDigit(event,this.value);"/>
function isDigit(evt, txt) {
var charCode = (evt.which) ? evt.which : event.keyCode
var c = String.fromCharCode(charCode);
if (txt.indexOf(c) > 0 && charCode == 46) {
return false;
}
else if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
Call this function from input textbox on onkeypress event

- 132
- 7
You can use RegularExpressionValidator
<asp:TextBox ID="viewTextBox" runat="server" Text="0"></asp:TextBox>
<asp:RegularExpressionValidator ID="viewRegularExpressionValidator" runat="server" ValidationExpression="[0-9]{1,50}" ControlToValidate="viewTextBox" ErrorMessage="Please Enter numbers only">*</asp:RegularExpressionValidator>

- 5,494
- 8
- 47
- 80
function CheckNumeric(event) {
var _key = (window.Event) ? event.which : event.keyCode;
if ((_key > 95 && _key < 106) || (_key > 47 && _key < 58) || _key == 8 || _key == 9 || _key == 37 || _key == 39 || _key == 190 || _key == 110) {
return true;
}
else {
return false;
}
}
<input type="text" onkeydown="return CheckNumerick(event);" />
Accept Keys: Numbers + NumPedNumbers + Tab + "," + "." + LeftButton + RightButton + Delete + BackSpace

- 645
- 7
- 13
we can use javascript code
function validateAlphaNumericCode(event) {
keyEntry = (event.which) ? event.which : event.keyCode
if (((keyEntry >= '65') && (keyEntry <= '90')) || ((keyEntry >= '97') && (keyEntry <= '122')) || (keyEntry == '37') || (keyEntry == '39') || (keyEntry == '46') || (keyEntry == '8') || (keyEntry == '9') || (keyEntry == '95') || ((keyEntry >= '48') && (keyEntry <= '57')))
return true;
else
return false;
}
validate this code with your textbox.

- 13,305
- 15
- 73
- 129

- 21
- 2
You might find useful microsoft msdn article How To: Use Regular Expressions to Constrain Input in ASP.NET. Take a look at "Common Regular Expressions" Table. It has validation example for
Non- negative integer
^\d+$
This expression validates that the field contains an integer greater than zero.

- 5,813
- 1
- 41
- 70
User below regular expression validator.
<asp:RegularExpressionValidator ID="RegularExpressionValidatorNumeric" runat="server" ControlToValidate="yourControl ID" ErrorMessage="Registraion ID Should be a Numeric" ValidationExpression="^\d+$" ></asp:RegularExpressionValidator>

- 1,220
- 15
- 22
I would use ASP.NET Ajax Filter TextBoxExtender control
https://www.aspsnippets.com/Articles/ASPNet-AJAX-FilteredTextBoxExtender-Control-Example.aspx

- 819
- 2
- 9
- 26
if (document.de.your_textbox_id.value != "")
{
var checkOK = "0123456789";
var checkStr = document.de.your_textbox_id.value;
var allValid = true;
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
}
}
if (!allValid)
{
alert("Please enter only numeric characters in the text box.");
document.de.your_textbox_id.focus();
}
}

- 13,305
- 15
- 73
- 129

- 458
- 1
- 4
- 15