JumpStart # 18– Deferred validation in ASP.Net 4.5 using requestValidationMode

Before looking at the code, Read about – What is JumpStart?

In ASP.Net 4.5, we can defer (lazy) validation of form fields by setting requestValidationMode attribute in httpRuntime section of web.Config file. By default, all the data coming through in request is subjective for validation. But if we want to defer the validation for form fields until they are accessed at runtime, we can set requestValidationMode attribute along with ValidateRequestMode to disabled for the controls of our interest.

Lets take a quick look into code. First create a ASP.Net 4.5 Website. Change the following in web.Config –

<httpRuntime targetFramework="4.5" requestValidationMode="4.5"/>

Now lets navigate to Default.aspx and add the following code by replacing the existing code –

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" ValidateRequestMode="Disabled"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
    </div>
</asp:Content>

If we do not want to validate TextBox1, simply access Unvalidated.Form[] of the Request Object –

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(Request.Unvalidated.Form[TextBox1.UniqueID]);
    }

When you enter “<h1>hi</h1>” in TextBox1, it is not going to validate that data. Based on Button1_Click event, it is going to display the data onto the page.

If we want to validate TextBox1, then unlike above scenario directly access the Form[] collection of Request Object. Have the following code in Button click-

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(Request.Form[TextBox1.UniqueID]);
    }

In this case, when we try to access Form[] collection, we get a HttpRequestValidationException as shown in below picture –

requestValidationMode1

Lastly, if we do not want to defer the validation till runtime, then we can change validationRequestMode in web.Config. In this case it will be defaulted for 4.0, which indicates that ASP.Net engine is going to validate all the form[] data.

<httpRuntime targetFramework="4.5" requestValidationMode="4.0"/>

We get –

requestValidationMode2

Important points to be remembered –

1. ValidateRequestMode=”disabled” for controls is required along with requrestValidationMode attribute to prevent validation.

2. Even though ValidateRequestMode is set to disabled, accessing Request.Form[] collection is going to give a validation exception. Instead access only Request.Unvalidated.Form[] collection. This behavior is because of the fact that requestValidationMode attribute conveys ASP.Net 4.5 to perform validation on Request.Form[] data access.

You may also like...