Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only integers in a textbox? [duplicate]

Tags:

asp.net

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

like image 562
Jui Test Avatar asked Mar 16 '12 05:03

Jui Test


People also ask

How do I allow only the numeric value in a text box?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I restrict a textbox to accept only numbers in C?

In our webpage with the definition of textbox we can add an onkeypress event for accepting only numbers. It will not show any message but it will prevent you from wrong input. It worked for me, user could not enter anything except number.


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

like image 136
Ashwini Verma Avatar answered Oct 11 '22 15:10

Ashwini Verma


<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> 
like image 30
Madhu Beela Avatar answered Oct 11 '22 16:10

Madhu Beela