ASP.NET: RequiredFieldValidator with Multiple TextBoxes in ListView

Eric Bergman picture Eric Bergman · Nov 5, 2012 · Viewed 13.6k times · Source

I have a ListView

<asp:ListView ....>
    <asp:TextBox ID="txtComment" ... />
    <asp:RequiredFieldValidator ID="rfvComment" ControlToValidate="txtComment" ... />
    <act:ValidatorCalloutExtender ID="vceComment" TargetControlID="rfvComment" ... />

    <asp:Button ID="btnAddComment" ... />

</asp:ListView>

lets say this ListView creates the following:

TextBox1 Button1

TextBox2 Button2

TextBox3 Button3

If I click on Button2 the RequiredFiledValidator/ValidatorCalloutExtender are applied to TextBox1 instead of TextBox2, if I click on Button3 the RequiredFiledValidator/ValidatorCalloutExtender are applied to TextBox1 as well, I want the RequiredFiledValidator/ValidatorCalloutExtender to apply to the TextBox next to the button, so if I click Button3 I want it to apply to TextBox3.

Does anyone know how can I achieve this?

thank you.

Answer

Yuriy Rozhovetskiy picture Yuriy Rozhovetskiy · Nov 5, 2012

Use ValidationGroup property and generate it value dynamically:

<asp:TextBox runat="server" ID="TextBox1" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TextBox1" Text="*"
    ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />
<asp:Button runat="server" Text="Click Me" ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />

Add script below at very bottom of form:

<script type="text/javascript">
    var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
    ValidatorUpdateDisplay = function (val) {
        originalValidatorUpdateDisplay.call(null, val);
        var isHidden = val.style.display == "none" || val.style.visibility == "hidden";

        var extender = Sys.UI.Behavior.getBehaviorsByType(val, Sys.Extended.UI.ValidatorCalloutBehavior);
        if (extender && extender.length == 1) {
            extender = extender[0];
            if (isHidden) {
                extender.hide();
            }
            else {
                extender.show(true);
            }
        }
    }
</script>

I suppose it would be better to customize toolkit source, but I'm not in the mood to do this :) So hope this script will fix your problem