Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Rangevalidator control in asp.net - Part 45

Suggested Videos
Part 42 - Asp.net panel control
Part 43 - Creating controls dynamically using asp.net panel control
Part 44 - RequiredField validator control in asp.net

In this video we will discuss about Rangevalidator control. This control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age falls between 1 and 100.

RangeValidator control in asp.net

In the HTML below, TextBox txtAge captures age of the person. If the user enter's any number that is not between 1 & 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, age is an integer, the Type is specified as integer.
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" 
    ErrorMessage="Age must be between 1 & 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" >
</asp:RangeValidator>



Properties specific to Rangevalidator control:
Type - This property, specifies the data type of the value to check. Data types supported include - Currency, Date, Double, Integer, String.
MinimumValue - The minimum value allowed
MaximumValue - The maximum value allowed

Comple HTML of the aspx page used in the Demo: Rangevalidator only checks if the entered data is within the allowed range. If you want to check for a required field, use RequiredFieldValidator. For the age field, we are using both RequiredFieldValidator and RangeValidator. Also notice that, in this example we are using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Because of this, the error message will always occupy the space on the screen even if the validation passes. This pushes "Age is Required" error message to the right. To correct this we have set Display="Dynamic". This renders the error message with style display:none. If a tag has this style, it will not occupy space when not visible.
<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server" 
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer" 
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge" 
            runat="server" ErrorMessage="Age is required" 
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server" 
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date" 
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px" 
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>



Code-Behind page code:
protected void btnSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.Color.Green;
        lblStatus.Text = "Data Saved successfully";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.Color.Red;
        lblStatus.Text = "Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls.
None - Error message not rendered and displayed next to the control. Used to show the error message only in the ValidationSummary control
Static - The error message is displayed next to the control if validation fails. Space is reserved on the page for the message even if validation succeeds. The span tag is rendered with style visibility:hidden
Dynamic - The error message is displayed next to the control if validation fails. Space is not reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

8 comments:

  1. Hai venkat,

    I am getting server error when running the above code.

    "The value '31/12/2012' of the MaximumValue property of 'RangeValidatorDateAvailable' cannot be converted to type 'Date'."

    This is what am getting when running the above code.

    ReplyDelete
  2. change the date to '12/31/2012'

    ReplyDelete
  3. The value '31/12/2012' of the MaximumValue property of 'RangeValidatorDateAvailable' cannot be converted to type 'Date'."

    ReplyDelete
  4. Your videos are very nicely presented and helpful to understand the concepts. How does the rangevalidator control behave for the datatype string or currency?

    Can you help us understand when to use the datatype = string or currency in the rangevalidator control?

    Thank you for sharing your knowledge.

    ReplyDelete
  5. Hello,

    I have a question:

    if (Page.IsValid)
    {
    lblStatus.ForeColor = System.Drawing.Color.Green;
    lblStatus.Text = "Data Saved successfully";
    }
    else
    {
    lblStatus.ForeColor = System.Drawing.Color.Red;
    lblStatus.Text = "Validation Failed! Data not saved";
    }
    In this case: if (Page.IsValid) it should show green. And it is working fine.
    However, if it is not true. It is not returning the else case.
    What it could be?

    ReplyDelete
    Replies
    1. I ran in to the same issue.

      In Part 47 is the answer.

      The issue is the default Validator behavior takes precedence over the Input, if the input has an error, it will give the error message, but the page will NOT be Posted - therefore the Click event will Not happen.

      I was also frustrated because the 'lblStatus' text was still visible, even though there was an error.

      But the Answer below, fixed the problem.


      Include in the Validator: EnableClientScript="false"

      Delete
  6. how i can give validation expression for only a specific domain for example abcd@abcd.edu.kk

    ReplyDelete

  7. WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

    Source Error:


    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

    Stack Trace:



    [InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).]
    System.Web.UI.ClientScriptManager.EnsureJqueryRegistered() +2871809
    System.Web.UI.WebControls.BaseValidator.RegisterUnobtrusiveScript() +11
    System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +9678381
    System.Web.UI.Control.PreRenderRecursiveInternal() +88
    System.Web.UI.Control.PreRenderRecursiveInternal() +160
    System.Web.UI.Control.PreRenderRecursiveInternal() +160
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4775


    Show this message. what will i do for solution.

    ReplyDelete

It would be great if you can help share these free resources