I have a required validation setup on a textbox, but I have to make sure it is an integer also.
how can I do this?
I have a required validation setup on a textbox, but I have to make sure it is an integer also.
how can I do this?
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.
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.
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
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.
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.