Reputation: 1686
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.
Upvotes: 1
Views: 3351
Reputation: 1758
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>
Upvotes: 2
Reputation: 116987
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.
Upvotes: 1
Reputation: 48088
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.
Upvotes: 0