[asp.net] How to allow only integers in a textbox?

In my form I want to allow typing of integer values only in a textbox. How to do that?

This question is related to asp.net

The answer is


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


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>

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>

An even easier method is to use the TextMode attribute:

<asp:TextBox runat="server" ID="txtTextBox" TextMode="Number">


Just use

<input type="number" id="foo" runat="server" />

It'll work on all modern browsers except IE +10. Here is a full list:

http://caniuse.com/#feat=input-number


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.


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


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..


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.


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


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();                            
    }
}

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>

<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>

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.


You can use client-side validation:

<asp:textbox onkeydown="return (!(event.keyCode>=65) && event.keyCode!=32);" />

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>

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>