Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validating jquery autocomplete

I have a textbox with remote datasource for autocomplete(jquery) [not the plugin, the original one shown in jquery ui demos ] How do I make sure user typed only what was in one of autocomplete suggestions and nothing of his own ?

like image 884
Shrinath Avatar asked Dec 08 '10 07:12

Shrinath


1 Answers

The question is lacking specifics, but I will assume you mean validate on the client side since you referred explicitly to the auto complete plugin. This answer will have two parts. The first is the original answer, assuming one autocomplete plugin. The second is revised based on updates to the question.

1) Using http://docs.jquery.com/Plugins/Autocomplete

The best solution for this is the "mustMatch" option. Here is the API documentation.

If set to true, the autocompleter will only allow results that are presented by the backend. Note that illegal values result in an empty input box.

You should be able to use it in this way:

$("selector").autocomplete("url", {"mustMatch": true});

You can also validate the user input in some way in the "result" event. Here is a link: http://docs.jquery.com/Plugins/Autocomplete/result .

2) Using http://jqueryui.com/demos/autocomplete

There is no mustMatch option here. You could extend the plugin, or you could add something similar to what I mentioned for the other autocomplete plugin. Use the "change" event.

$( ".selector" ).autocomplete({
   change: function(event, ui) { ... }
});

If you were using an array as a datasource, this would be more efficient. Since you are using a remote data source you would need to do another final query using ui.item to validate the user value. You can then allow or deny the default behavior.

In either case, the input should still be validated in some way on the server side. This is out of the scope of jQuery plugins.

like image 82
jthompson Avatar answered Oct 12 '22 23:10

jthompson