Tuesday, April 10, 2012

RangeValidator in Asp.Net

The RangeValidator is used to make sure that the user enters a value within a pre-defined range of values, this validate is often used to validate numeric value inputs from the user.

The below code snipet adds a TextBox to an Asp.net form and associates an Asp.Net RangeValidator to the text box to make sure that the text box accepts only values in the range 1.. 1000


<asp:TextBox
ID="txtID"
runat="server"
MaxLength="25">
</asp:TextBox>

<asp:RangeValidator
ID="valtxtID "
runat="server"
ControlToValidate="txtID"
          Display="Dynamic"
ErrorMessage="Please enter a valid number (1..1000)."
MinimumValue="1"
MaximumValue="1000"
Type="Integer"
SetFocusOnError="True">*
</asp:RangeValidator>

The above RangeValidator makes sure that only numeric values in the range 1..1000 are entered in the txtID textbox, any other values will lead to an error message prompt.

The RangeValidator also takes care of the datatype of the value which is entered in the TextBox, the
Type="Integer" property makes sure that only Integer values are entered into the TextBox.

Finally add a ValidationSummary control to consolidate all the validations in the page.


<asp:Button ID="cmdSave"
runat="server"
Text="Save"
OnClick="cmdSave_Click" />
              
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
      ShowSummary="False"
EnableClientScript="true" />
</asp:ValidationSummary>

Once we are done with the code in the .aspx page, we should also make sure that the validations are passed in the server side in the .vb/.cs code behind file.

Asp.Net performs the validations both in the client and the server side, of the users' browser doesn’t support JavaScript then the client side validation might get skipped, however the same validation in done by Asp.Net in the server side also. 

The Page.IsValid property returns true if the server side validations are succesful, else it will return false, hence we need to make sure that the Page.IsValid property is true before proceeding with the other operations.

if (Page.IsValid)
{
   //DB save and other server side logic goes here
}
 
That’s it we have seen, how to use the RangeValidator to validate user input in an Asp.net form.

Search Flipkart Products:
Flipkart.com

No comments: