This post is over 6 months old. Some details, especially technical, may have changed.

ValidateInputAttribute Changes in MVC3 (Beta 2)

This post is now redundant with the release of ASP.NET MVC 3 RC 1.  SkipRequestValidation is the new ValidateInputAttribute(Exclude="").  Read More.

The ValidateInputAttribute has received a nice little tweak in MVC 3 offering more fine grained control over parameters of a request. 

In MVC 2 using ValidateInputAttribute was limited to the request level, that is all parameters in the request where either validated or not.  Lets demonstrate this with a simple example - a simple forum posting page,

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Common.Model.ForumPost>" %>

<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
	Login
</asp:Content>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <h2>Post Question</h2>
    <% using (Html.BeginForm()) { %>
        <p>
            <%=Html.LabelFor(c => c.Subject)%>
            <%=Html.TextBoxFor(c => c.Subject)%>
        </p>
        <p>
            <%=Html.LabelFor(c => c.Body)%>
            <%=Html.TextAreaFor(c => c.Body)%>
        </p>
        <input type="submit" value="Post" />
    <%} %>
</asp:Content>

We don;t care what the controller actions actually do but lets describe them here anyway

public class HomeController : Controller
{
    public ActionResult Post()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Post(ForumPost post)
    {
        return View();
    }
}

Now attempting to post any sort of markup back to the action will result in an exception being thrown,

[[posterous-content:DasrjrabrrcEcDeiHdeG]]

If we wanted to allow markup to go through we can add the [ValidateInput(false)] attribute to the action.  The only problem with that is if we only wanted to allow markup in the Body and not the Subject we would have to write our own tests in the controller to prevent this.  Not the most ideal or clean solution.

MVC 3 solves this quite simply by extending the ValidateInputAttribute and allowing use to specify exclusions.  This means we can have validation turned on but specifically state the we don't want to validate a specific request parameter(s) (e.g. Body).

[ValidateInput(true, Exclude = "Body")]

A very minor tweak that makes a big leap to being able to produce cleaner more readable code.

Published in .NET on October 23, 2010