After incorporating what I’ve learned by reading the answers to this question, I’ve figured out how to generate an error message when, in an autocomplete field the user enters text that doesn’t correspond to any of the available selections.
This page is an ASP.NET page which already has an infrastructure of ASP.NET validators on it. What I want to happen is to introduce a validator onto the page that causes page validation to fail when the user enters something not in the list. Here’s what I have so far:
I started with Anonymous’s answer to the question above:
change: function (event, ui) {
if (!ui.item) {
$(this).val('');
}
}
I replaced it with this in my autocomplete() javascript:
change: function (event, ui) {
if (!ui.item) {
$(""#" + lblAutocompleteError.ClientID + @""").show();
$(""#" + txtDummy.ClientID + @""").val('');
} else {
$(""#" + lblAutocompleteError.ClientID + @""").hide();
$(""#" + txtDummy.ClientID + @""").val('Dummy');
}
},
It’s javascript that’s being generated in code-behind rather than on the front end, that’s why it has all that literal string goodness…
And on the front end, I’ve declared two controls: txtDummy which I set and clear based on whether the autocomplete contains a matching string, and rfvDummy that requires said TextBox to be populated.
<asp:RequiredFieldValidator runat="server" ID="rfvDummy"
ControlToValidate="txtDummy" />
<asp:TextBox runat="server" ID="txtDummy" Text="Dummy" Visible="false" />
Problem is, the RequiredFieldValidator isn’t failing when it should. More importantly, I get this sinking feeling that I’m going down the wrong path here. Creating a hidden TextBox and a RequiredFieldValidator seems like way too much of a hack for what I’m trying to accomplish. Is there a straightforward way to cause a page to fail validation, on the client side, with a message formatted like my other validators, when the user enters a value that is not in the autocomplete list?
My autocomplete logic was correct, it was the means of hiding the
txtDummycontrol that was not. By usingthe HTML for
txtDummyis not generated, so theRequiredFieldValidatorhas nothing to look at. Changing the code for theTextBoxto:allowed the HTML to be generated. When my
changeclause, above, is invoked, the page now fails validation when a matching item is not selected in theTextBox.