How to allow only integers in a textbox?

asp.net

asp.net Problem Overview


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

asp.net Solutions


Solution 1 - asp.net

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.

Solution 2 - asp.net

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

Solution 3 - asp.net

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>

Solution 4 - asp.net

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

Solution 5 - asp.net

An even easier method is to use the TextMode attribute:

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

Solution 6 - asp.net

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>

Solution 7 - asp.net

You can use client-side validation:

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

Solution 8 - asp.net

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

Solution 9 - asp.net

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.

Solution 10 - asp.net

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>

Solution 11 - asp.net

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

Solution 12 - asp.net

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

Solution 13 - asp.net

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>

Solution 14 - asp.net

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.

Solution 15 - asp.net

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

Solution 16 - asp.net

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

Solution 17 - asp.net

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.

Solution 18 - asp.net

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>

Solution 19 - asp.net

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJui TestView Question on Stackoverflow
Solution 1 - asp.netAshwini VermaView Answer on Stackoverflow
Solution 2 - asp.netMadhu BeelaView Answer on Stackoverflow
Solution 3 - asp.netVinodView Answer on Stackoverflow
Solution 4 - asp.netEIVView Answer on Stackoverflow
Solution 5 - asp.netA-SharabianiView Answer on Stackoverflow
Solution 6 - asp.netAnusha BusettyView Answer on Stackoverflow
Solution 7 - asp.netbbhView Answer on Stackoverflow
Solution 8 - asp.netmexrodView Answer on Stackoverflow
Solution 9 - asp.netKrisztián BallaView Answer on Stackoverflow
Solution 10 - asp.netrdansView Answer on Stackoverflow
Solution 11 - asp.netAli KaracaView Answer on Stackoverflow
Solution 12 - asp.netAmit MaruView Answer on Stackoverflow
Solution 13 - asp.netyogihostingView Answer on Stackoverflow
Solution 14 - asp.netaditi mittalView Answer on Stackoverflow
Solution 15 - asp.netVolkanCetinkayaView Answer on Stackoverflow
Solution 16 - asp.netPrabhavithView Answer on Stackoverflow
Solution 17 - asp.netDeveloper Marius ŽilėnasView Answer on Stackoverflow
Solution 18 - asp.netmzonerzView Answer on Stackoverflow
Solution 19 - asp.netbizimundaView Answer on Stackoverflow