Friday, 16 March 2012

Regular Expression Validator to allow only integer (numbers) not string in textbox asp.net c#

How to use regular expression validator to allow only integer (numbers) not string in textbox in asp.net c#

Javascript or Jquery not required to validate numeric  character not string. We can simply use regex validation control to achive this.

Sample code:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Numbers Only allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>

To allow specific count of numbers, use the following regex expression

 ValidationExpression="^\d{7}$">  //Allows only 7 digit of char
 ValidationExpression="^\d{10}$">  //Allows only 10 digit of char