0

Hi I'm a beginner in Asp.net actually I'm trying to prevent the user from inserting letter in the phone number text box, I am trying this code but it doesn't work.

private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
{
    char ch = e.KeyChar;
    if (!Char.IsDigit(ch) && ch !=8)
    { 
        e.Handled = true;
    }
}
Abslen Char
  • 3,071
  • 3
  • 15
  • 29
Amjad
  • 9
  • 3
  • KeyPress is probably is too late. Check PreviewKeyPress event. Usually these kind of things are done in JavaScript isnt it? – Prateek Shrivastava Mar 19 '18 at 08:28
  • 4
    That's a winforms event. You have to use javascript to achieve the same in webforms since you want to suppress keys when the client enters something in a textbox in the browser. But i'd suggest to use a different way, validate with ASP.NET validators. – Tim Schmelter Mar 19 '18 at 08:29
  • 1
    Possible duplicate of [prevent user from enter non-numeric data in ASP.NET textboxes](https://stackoverflow.com/questions/7763779/prevent-user-from-enter-non-numeric-data-in-asp-net-textboxes) – PNP Mar 19 '18 at 08:47
  • Instead of looking at the duplicate you should really use ASP.NET validators, f.e. the `RegularExpressionValidator` with a regex you can find here: [A comprehensive regex for phone number validation](https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Tim Schmelter Mar 19 '18 at 09:05

3 Answers3

0

This seems to be from winforms or wpf. Try something like this in aspx:

<asp:TextBox ID="TxtNo" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" 
runat="server" ErrorMessage="Enter valid Phone number" 
ControlToValidate="TxtNo" 
ValidationExpression= "^([0-9\(\)\/\+ \-]*)$"></asp:RegularExpressionValidator>
Praneet Nadkar
  • 823
  • 7
  • 16
0

As most commented there, you have to use JavaScript function to enable this validation. Go through this stackoverflow thread which describe same scenario you are now facing. prevent user from enter non-numeric data in ASP.NET textboxes

PNP
  • 361
  • 5
  • 17
0

Try this sample:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" TargetControlID="TextBox1" FilterType="Numbers" />

Referance: https://www.c-sharpcorner.com/uploadfile/prathore/ajax-filteredtextboxextender/

Leo
  • 398
  • 6
  • 11