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.
<p> <asp:ValidationSummary ValidationGroup="*" runat="server" /> </p> <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" /> <p> <asp:Button Text="Save Draft" onclick="OnSaveDraft" runat="server" /> <asp:Button Text="Submit" onclick="OnSubmit" ValidationGroup="Submit" runat="server" /> </p>
Then drop this near the bottom of your Page or Master Page:
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.