asp.net validation to make sure textbox has integer values

This works fine to me:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
     ControlToValidate="YourTextBoxID"
     ErrorMessage="Only numeric allowed." ForeColor="Red"
     ValidationExpression="^[0-9]*$" ValidationGroup="NumericValidate">*
</asp:RegularExpressionValidator>

I think you should add ValidationGroup="NumericValidate" to your submit button also.


If all that you are concerned about is that the field contains an integer (i.e., not concerned with a range), then add a CompareValidator with it's Operator property set to DataTypeCheck:

<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer" 
 ControlToValidate="ValueTextBox" ErrorMessage="Value must be a whole number" />

If there is a specific range of values that are valid (there probably are), then you can use a RangeValidator, like so:

<asp:RangeValidator runat="server" Type="Integer" 
MinimumValue="0" MaximumValue="400" ControlToValidate="ValueTextBox" 
ErrorMessage="Value must be a whole number between 0 and 400" />

These will only validate if there is text in the TextBox, so you will need to keep the RequiredFieldValidator there, too.

As @Mahin said, make sure you check the Page.IsValid property on the server side, otherwise the validator only works for users with JavaScript enabled.


You can use java script for this:-

<asp:TextBox ID="textbox1" runat="server" Width="150px" MaxLength="8" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;"></asp:TextBox>

Use Int32.TryParse.

 int integer;
 Int32.TryParse(Textbox.Text, out integer)

It will return a bool so you can see if they entered a valid integer.