asp.net validation to make sure textbox has integer values

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.

Leave a Comment