views:

825

answers:

3

I would like to use a Validator to guarantee that a given textbox's submitted content is unique. I want to make sure that the name put into the box is not the same as any other text box.

The catch is I don't know at compile time how many other text boxes it will be compared to. It could be anywhere from 0 - n other name text boxes.

Thanks for any help you can give.

A: 

I think you should use Custom Validator instead of Compare Validator. In client side or server side store all control's values to an array and check if the item is in the array.

Here is a good sample of CustomValidator.

Canavar
+1  A: 

I'm not sure how you want it to look on your UI in terms of error messages, but you can accomplish this with a CustomValidator control on the page.

When the ServerValidate event fires, simply find all your textboxes on the page, using FindControl() or whatever else is easiest, maybe you have them in a collection already.

A simple way to check unique values would be to try to add the values to a Dictionary<string, Textbox>, keyed by the text value. The Add method would throw an exception if the key already existed.

womp
+2  A: 

If you want to do it on the client, a simple way, though maybe not the best one is something like this:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function CheckUnique(sender, args) {
            var inputArray = document.getElementsByTagName("input");
            for (var i = 0; i < inputArray.length; i++) {
                if (inputArray[i].type == "text" && inputArray[i].id != "TextBox1" && inputArray[i].value == args.Value) {
                    args.IsValid = false;
                    return;
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="CustomValidator" ClientValidationFunction="CheckUnique"></asp:CustomValidator>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>
SirDemon
to clarify. EACH of the textboxes have to be unique...
Matt Dunnam
Then forget the ControlTOValidate attribute and do the loop for each TextBox control. The Validation should fire when clicking the submit button anyway. The args.Value will be useless to you then, of course.
SirDemon