Click here to Skip to main content
15,891,721 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I want validation for text box in a text box enter only digits. I want code in Asp.net but in this keypress event not available.
How to get key press event?
Posted
Updated 19-Aug-10 7:59am
v2
Comments
Sandeep Mewara 19-Aug-10 15:16pm    
You Javascript to trap the event.

Hi

You add key press event in the code behind file as below

protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Attributes.Add("onkeypress", "javascript:return allownumbers(event);");
    }

and write the Javascript function as below in the aspx page

function allownumbers(e)
  {
   var key = window.event ? e.keyCode : e.which;
   var keychar = String.fromCharCode(key);
   var reg = new RegExp("[0-9.]")
   if (key == 8)
   {
    keychar = String.fromCharCode(key);
   }
   if (key == 13)
   {
    key=8;
    keychar = String.fromCharCode(key);
   }
   return reg.test(keychar);
  }
 
Share this answer
 
Comments
Member 366901 29-Apr-13 21:36pm    
this is a test
Try this:

XML
<asp:TextBox ID="TextBox1" onkeyup="Page_ClientValidate();" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only numeric data allowed."
            Display="Dynamic" ValidationExpression="\d+" ControlToValidate="TextBox1"></asp:RegularExpressionValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" />


At each key press, this code tests whether the input is Numeric or not. If input is not numeric, validation message is shown.
 
Share this answer
 
Comments
Sandeep Mewara 19-Aug-10 15:16pm    
Reason for my vote of 1
ASP:Textbox is a server control and it won't have a client side onkeyup event exposed.
Al-Farooque Shubho 19-Aug-10 23:24pm    
Well, you are wrong.

Ideally, the "onkeyup" attribute should be added in CodeBehind. But, it doesn't mean that, it can't be added in the markup. You can add it and it works quite fine.

I added it in markup so that, the question author can understand it easily.

Just run the code in an aspx page in Visual Studio and see what is the output. I'd request you to consider re-vote after seeing the output.

Thanks.
eebert 18-Jul-12 10:32am    
Works perfectly. This solves the problem of how to validate on each keystroke. Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900