Search code examples
unobtrusive-validationjquery-tokeninput

Jquery tokeninput and unobtrusive validation in a MVC 4 application


I am stuck here and would very much appreciate help. I have a form in a razor view with a input field for current city which looks like this:

@Html.LabelFor(x => x.UserModel.CurrentCity)
@Html.TextBoxFor(x => x.UserModel.CurrentCity, new { @data_bind = "value: UserModel.CurrentCity ", @class = "city", @data_val = "true", @data_val_required="City is required" })
@Html.ValidationMessageFor(x => x.UserModel.CurrentCity)

I want autocomplete for this field and am using jquery token input plugin for this like:

$(".city").tokenInput('@Url.Action("AutocompleteCity", "Settings")',{ minChars: 2, tokenLimit: 1, hintText: "Type in a city" });
$(".city").tokenInput("add", {name: viewModel.UserModel.CurrentCity()});

Everything works fine except the clientside unobtrusive validation. The form gets posted even if CurrentCity is empty.

I also tried to change the MVC helpers to plain html:

<input data-val="true" data-val-required="City is required" type="text" class="city" data-bind = "value: UserModel.CurrentCity, attr: { name: 'UserModel.CurrentCity', id: 'UserModel.CurrentCity'}" />
<span class="field-validation-valid" data-valmsg-for="UserModel.CurrentCity" data-valmsg-replace="true"></span>

This approach prevents the form from being submitted but the validation-error class is not injected into the span and the error message does not show up.

Any suggestions?


Solution

  • The original input element you created is hidden. You will likely need to enable validation of hidden elements: jquery.validate v. 1.9 ignores some hidden inputs or https://stackoverflow.com/a/13295938/173225.