I'm trying to validate an autocomplete field using ASP.NET MVC and I have a doubt. I'll describe the scenario below:
Currently, i'm retrieving the values from an Ajax call in the Form
controller, like this:
$("#AutoComplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "/form/AjaxCall",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.nome, value: item.nome };
}))
}
})
},
});
My Form
controller:
public ActionResult AjaxCall(string term)
{
var result = (from r in db.Elementoes
where r.nome.ToLower().Contains(term.ToLower())
select new { r.nome }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
My View field:
@Html.TextBoxAutoCompleteFor(model => model.AutoComplete)
Let's suppose that the available values on the autocomplete are: Acre, Piracicaba and Jundiaí
How can I validate the user's input to the field (client and server-side) and show a validation message like: "the text wasn't found on the database?" Example: If he types Acre it's ok, but if he types Acre3 the error is showed while typing?
Some points to consider:
1 - I cannot set the autocomplete value to empty if the value isn't correct, i need to show the message.
2 - I cannot set the error class manually in jQuery. I need to use jQuery unobtrusive validation.
I referred to the following articles, but those solutions doesn't worked:
MVC validation with autocomplete field
Thanks in advance!