ASP.NET Selective Validation Hack

Scenario: using classic ASP.NET Web Forms, we have a data entry page. On the bottom of the page are two buttons: "Save Draft" and "Submit."

When a user Saves a Draft, we want to do some validation, but not all. We want to make sure only numbers are entered for numeric fields, yet we don't need all required fields to be filled out. But when a user Submits the document, all validation should occur.

ASP.NET doesn't support this very nice. Validation Groups get us close, but are meant to work on completely different sets of validators. In our case, one set of validators is a subset of the other. Things get especially dicey if you throw a ValidationSummary onto the page.

With one JavaScript hack that can go in your Master Page you can get the desired behavior. First, the ASP.NET markup:

    <asp:ValidationSummary ValidationGroup="*" runat="server" />

<asp:TextBox ID="SomeNumber" runat="server" />
<asp:RequiredFieldValidator ValidationGroup="Submit"
    Text="Required" ErrorMessage="SomeNumber is required."
    ControlToValidate="SomeNumber" Display="Dynamic"
    runat="server" />
<asp:RangeValidator Type="Integer" MinimumValue="0" MaximumValue="100"
    Text="Number" ErrorMessage="SomeNumber must be [0, 100]."
    ControlToValidate="SomeNumber" Display="Dynamic"
    runat="server" />

    <asp:Button Text="Save Draft" onclick="OnSaveDraft" runat="server" />
    <asp:Button Text="Submit" onclick="OnSubmit" ValidationGroup="Submit" runat="server" />

Then drop this near the bottom of your Page or Master Page:

<script type="text/javascript">
// Override this part of ASP.NET validation in order to make validation
// groups work as subsets of each other rather than completely independently.
function IsValidationGroupMatch(control, validationGroup) {
    if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
        return true;
    var controlGroup = "";
    if (typeof (control.validationGroup) == "string") {
        controlGroup = control.validationGroup;
    return (controlGroup == validationGroup || controlGroup == '*' || validationGroup.length > 0);

The method IsValidationGroupMatch() is supplied by ASP.NET client-side validation. We override that method and add the highlighted bit to it.

Caveat 1: This won't affect server-side validation, so to be thorough the OnSubmit in the code behind should have at the top, Validate(""); if(!Page.IsValid) return;

Caveat 2: This will probably cause problems if you want to use Validation Groups in the way they were originally intended, as completely isolated sets of validators.

Comments !