[asp.net] asp.net validation to make sure textbox has integer values

I have a required validation setup on a textbox, but I also have to make sure it is an integer.

How can I do this?

This question is related to asp.net validation

The answer is


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.


Double click your button and use the following code :-

protected void button_click(object sender,EventArgs e)
{
 int parsedValue;
 if(int.TryParse(!txt.Text,out parsedValue))
 {
 Label.Text = "Please specify a number only !!"; //Will put a text in a label so make     
    //sure                
  //you have a label
 }
 else
  {
    // do what you want to  
  }

There are several different ways you can handle this. You could add a RequiredFieldValidator as well as a RangeValidator (if that works for your case) or you could add a CustomFieldValidator.

Link to the CustomFieldValidator: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator%28VS.71%29.aspx

Link to MSDN Article on ASP.NET Validation: http://msdn.microsoft.com/en-us/library/aa479045.aspx


Visual Studio has got now integrated support for range checking and type checking :-

Try this :- For RANGE CHECKING Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-

View>Toolbox>Validation

Now Drag on RangeValidator to your design page where you want to show the error message(ofcourse if user is inputting out of range value) now click on your RangeValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write :-

Number must be in range.

Now select on Control to validate and select your TextboxID (or write it anyways) from the drop down.Locate Type in the property bar itself and select down Integer.
Just above it you will find maximum and minimum value .Type in your desired number .

For Type checking (without any Range)
Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-

View>Toolbox>Validation

Now Drag on CompareValidator to your design page where you want to show the error message(ofcourse if user is inputting some text in it). now click on your CompareValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write:-

Value must be a number .

Now locate ControltoValidate option and write your controlID name in it(alternatively you can also select from drop down).Locate the Operator option and write DataTypeCheck(alternatively you can also select from drop down)in it .Again locate the Type option and write Integer in it .

That's sit.

Alternatively you can write the following code in your aspx page :- <%--to validate without any range--%>


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>

http://msdn.microsoft.com/en-us/library/ad548tzy%28VS.71%29.aspx

When using Server validator controls you have to be careful about fact that any one can disable javascript in their browser. So you should use Page.IsValid Property always at server side.


<script language="javascript" type="text/javascript">
        function fixedlength(textboxID, keyEvent, maxlength) {
            //validation for digits upto 'maxlength' defined by caller function
            if (textboxID.value.length > maxlength) {
                textboxID.value = textboxID.value.substr(0, maxlength);
            }
            else if (textboxID.value.length < maxlength || textboxID.value.length == maxlength) {
                textboxID.value = textboxID.value.replace(/[^\d]+/g, '');
                return true;
            }
            else
                return false;
        }
 </script>

<asp:TextBox ID="txtNextVisit" runat="server" MaxLength="2" onblur="return fixedlength(this, event, 2);" onkeypress="return fixedlength(this, event, 2);" onkeyup="return fixedlength(this, event, 2);"></asp:TextBox> 

simpally add this code:

<asp:FilteredTextBoxExtender ID="txtAltitudeMin_FilteredTextBoxExtender" runat="server" Enabled="True" TargetControlID="txtAltitudeMin" FilterType="Numbers"></asp:FilteredTextBoxExtender>


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.


Attach a Regular Expression Validator to the text box and make its expression be this:

^\d+$

And do your server side validation too, of course.