views:

37

answers:

1

I have a table with 5 rows and 2 columns. Each cell contains a text box. I want to show error if one of the text boxes in each column is empty. I want both text boxes in a row shld be filled or both shld empty.

How can i do this via Asp.net validation controls?

I want to extend CompareValidator so that it will validate only if the controlToValidate and controlToCompare both have some text in it or both are empty.

A: 

You would need to use a CustomValidator and handle its ServerValidate event (and, optionally, its ClientValidationFunction for client-side validation). You could do one on the page and check all the rows, or you could have one per row and use the ControlToValidate property to give you context to the row you're validating.

Any example of the client-side validation is going to depend on your layout and any JavaScript framework that you're using. It might look something like this:

<table>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox11" /></td>
        <td><asp:TextBox runat="server" ID="TextBox12" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox21" /></td>
        <td><asp:TextBox runat="server" ID="TextBox22" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox31" /></td>
        <td><asp:TextBox runat="server" ID="TextBox32" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox41" /></td>
        <td><asp:TextBox runat="server" ID="TextBox42" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox51" /></td>
        <td><asp:TextBox runat="server" ID="TextBox52" /></td>
    </tr>
</table>
<asp:CustomValidator ID="TextBoxPairValidator" runat="server" ControlToValidate="TextBox11" ClientValidationFunction="TextBoxPairValidator_ClientValidate" />

<script type="text/javascript">
    (function () {
        window.TextBoxPairValidator_ClientValidate = function (sender, args) {
            var other = document.getElementById(sender.id.slice(0, -1) + '2');
            args.IsValid = (sender.value === '' && other.value === '')
                           || (sender.value !== '' && other.value !== '');
        };
    }());
</script>

That example obviously assumes a fairly simple layout, and fairly static naming (i.e. if your controls are in a naming container, you may not be able to use the ID trick to go from one text box to the other). Hopefully that's enough to get you started.

bdukes
any code example?
coure06