Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
3.4k views
in .Net Framework by 66 69 85

In the ASP.NET solution, I have a form that holds a textbox and I need to allow the user to only write numbers without letters in this textbox, How to add number validation only to textBox in asp.net?


1 Answer

0 like 0 dislike
by 66 69 85
edited by

How to validate textbox to only numbers in ASP.NET?

You can validate numbers by using Regular Expressions in ASP.NET by doing the following steps:

  1. In your Project, Add RegularExpressionValidator, you can add it through Toolbox.
  2. Click on RegularExpressionValidator, then click F4 to open properties.
  3. In the properties, find ValidationExpreesion property write the following Expression ^\d+$, as the below image
  4. Write your ValidationGroup you want for me : OnlyNumbers, as the below image
  5. Don't forget to set the ControlToValidate to your TextBox ID, in our case it's "txt_Numbers"

How to validate textbox to only numbers in ASP.NET?
6. write your ErrorMessage you want to display, for me: Enter only numbers!

The RegularExpressionValidator should be like that:

<asp:RegularExpressionValidator ID="ValidatNumbers" runat="server" ControlToValidate="txt_Numbers"
ErrorMessage="write only numbers" ValidationExpression="^\d+$" 
ValidationGroup="OnlyNumbers"></asp:RegularExpressionValidator>
  1. Add your ValidationGroup To your textbox and your button, as the image below:
    Number Validation in ASP.NET

Finally the output for your textbox, button and RegularExpressionValidator:

 <asp:TextBox ID="txt_Numbers" runat="server" ValidationGroup="OnlyNumbers"></asp:TextBox>

<asp:RegularExpressionValidator ID="ValidatNumbers" runat="server" ControlToValidate="txt_Numbers"
    ErrorMessage="write only numbers" ValidationExpression="^\d+$" 
    ValidationGroup="OnlyNumbers"></asp:RegularExpressionValidator>

<asp:Button ID="btnSubmit" Text="Submit" runat="server" ValidationGroup="OnlyNumbers" />
If you don’t ask, the answer is always NO!
...