Click here to Skip to main content
11,927,190 members (55,311 online)
Rate this:
Please Sign up or sign in to vote.
See more: ASP.NET
      I want validation for text box in a text box enter only digits. I want code in but in this keypress event not available.
How to get key press event?
Posted 19-Aug-10 7:48am
Edited 19-Aug-10 8:59am
Abhinav S407.8K
Sandeep Mewara 19-Aug-10 15:16pm
You Javascript to trap the event.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2


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)
    keychar = String.fromCharCode(key);
   return reg.test(keychar);
Member 366901 29-Apr-13 21:36pm
this is a test
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Try this:

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

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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.151126.1 | Last Updated 19 Aug 2010
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100