1. Use Page.GetValidators("Group") to get the validators in the other group
2. Check for invalid validators, create dummy ivalidators for invalid validators keeping same error message.
3. Add ivalidators in existing page means we are adding a new ivalidator with no validationgroup.
4. Now use Page.Validate();
Example:
1. Suppose there are two textboxes(txt1,txt2) and their requirefieldvalidator belong to different validation group(group1 and group2).
2. Drag a button and set its causesvalidation false.
3. Drag a validationsummary
Now code will look like
<form id="form1" runat="server">
<asp:TextBox ID="txt1" runat="server" Height="22px" Width="128px"></asp:TextBox>
<asp:RequiredFieldValidator ID="req" runat="server"
ErrorMessage="1 is required" ControlToValidate="txt1"
ValidationGroup="group1" SetFocusOnError="True">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="2 is required" ControlToValidate="txt2"
ValidationGroup="group2">*</asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" CausesValidation="False"
onclick="Button1_Click" Text="Button" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</form>
On button click we have to check both validationgroup group1 and group2:
protected void Button1_Click(object sender, EventArgs e)
{
AddControl("group1");
AddControl("group2");
Page.Validate();
}
protected void AddControl(string groupName)
{
foreach (IValidator i in Page.GetValidators(groupName))
{
i.Validate();
if (!i.IsValid)
{
Page.Validators.Add(new DummyValidator(i.ErrorMessage));
}
}
}
To create dummyivalidator
internal class DummyValidator : IValidator
{
private string errorMsg;
public DummyValidator(string msg)
{
errorMsg = msg;
}
public string ErrorMessage
{
get { return errorMsg; }
set { errorMsg = value; }
}
public bool IsValid
{
get { return false; }
set { }
}
public void Validate()
{
}
}
Note:
1. Button “CausesValidation” property must be false
2. No validation group must be assigned to button and validationsummary.
I made a custom validationsummary control based on this logic. Click here to see it.
I have a comment on this custom validator... I've used it to add my custom server side validation to a validationsummary control fine; however, when I try to assign a validation group to the custom control it does nothing. For example here is what I'm looking to do..
ReplyDeleteDim CustomSummary As New ValidationSummaryControl
CustomSummary.ValidationGroup = "Test"
CustomSummary.AddErrorMessage("Test is Required", Me)
Right now it's just not picking it up and not adding it to the validationsummary. If I take off the group it works fine.
Any help would be great!
Thanks
Lee