ValidationSummary not working when ValidationGroup is specified
I have a few section in an ASP.NET page and need to validate them separately.
Each section has it's own validation summary section so I thought of using the ValidationSummary tag with the ValidationGroup
attribute but it does not work.
The following code wo开发者_如何学编程rks but validates all controls in the page:
<asp:TextBox ID="field1" runat="server" TabIndex="1" MaxLength="20" />
<asp:RequiredFieldValidator ID="field1RequiredValidator" ControlToValidate="field1" runat="server"
Display="None" ErrorMessage="mandatory 1" />
<asp:TextBox ID="field2" runat="server" TabIndex="2" MaxLength="20" />
<asp:RequiredFieldValidator ID="field2RequiredValidator" ControlToValidate="field2" runat="server"
Display="None" ErrorMessage="mandatory 2" />
....
<asp:ValidationSummary ID="validationSummary" HeaderText="Sumary" runat="server" />
While the following does not work (no validation whatsoever, on submit I just go to the next page in the wizard):
<asp:TextBox ID="field1" runat="server" TabIndex="1" MaxLength="20" />
<asp:RequiredFieldValidator ID="field1RequiredValidator" ControlToValidate="field1" runat="server"
Display="None" ErrorMessage="mandatory 1" ValidationGroup="xxxx" />
<asp:TextBox ID="field2" runat="server" TabIndex="2" MaxLength="20" />
<asp:RequiredFieldValidator ID="field2RequiredValidator" ControlToValidate="field2" runat="server"
Display="None" ErrorMessage="mandatory 2" ValidationGroup="xxxx" />
....
<asp:ValidationSummary ID="validationSummary" HeaderText="Sumary" runat="server" ValidationGroup="xxxx" />
What am I missing here? Is there extra setup needed or something else?
The default behaviour in ASP.NET is that when the user clicks a button that has no ValidationGroup
specified (and has CausesValidation
set to true
), all validation controls that do not belong to a validation group are validated.
Therefore, to validate a specific group, you need to set the ValidationGroup
property of the button that should cause the validation (and also possibly the CausesValidation
property).
See the MSDN documentation for Button.ValidationGroup for details and an example.
EDIT: If you need to validate ALL groups on the page, the easiest way is of course to not use validation groups at all. If you however want to validate only some (but more than one) groups, you can do it on the server (in the click handler of the button) by calling:
Validate("groupOne");
Validate("groupTwo");
// ...
Note that this won't trigger client-side validation. See for example this post for a discussion about triggering multiple validation groups on a single button click.
EDIT: I found a blog post describing how to build a reusable "multiple validation group button" for ASP.NET, complete with code. Haven't tried it, but it looks promising.
精彩评论