I have a hidden field on my form that is required. The hidden field is populated when a user selects a value from a textbox using jQuery UI autocomplete. I have setup my form validator to not ignore hidden fields so that the validation actually works. The validation does work, but when a user selects the desired option from the autocomplete, which then populates the hidden field, the validation message will not clear and will show until the form is posted. Do I need to manually call $('form').validate() or something once the hidden field gets set or is there a way to have this clear without any extra javascript code?
My View Model:
public class IndexViewModel
{
public string SchoolName { get; set; }
[Required]
public int SchoolId { get; set; }
}
My View:
@model IndexViewModel
@using (Html.BeginForm())
{
<p>
@Html.LabelFor(m => m.SchoolName)
@Html.TextBoxFor(m => m.SchoolName)
@Html.HiddenFor(m => m.SchoolId)
@Html.ValidationMessageFor(m => m.SchoolId)
</p>
<p>
<input type="submit" />
</p>
}
@section scripts {
<script>
$(function () {
// stop validator from ignoring hidden fields
var validator = $('form').data('validator');
validator.settings.ignore = "";
// schoolname autocomplete
$('#SchoolName').autocomplete({
minLength: 1,
source: [
{ label: "ABC University", value: "1" },
{ label: "Oklahoma University", value: "2" },
{ label: "Texas University", value: "3" }
],
select: function (e, ui) {
e.preventDefault();
$('#SchoolId').val(ui.item.value);
$('#SchoolName').val(ui.item.label);
}
});
});
</script>
}
Thanks in advance.
Edit
Sparky, here is the rendered HTML:
<form action="/" method="post">
<p>
<label for="SchoolName">SchoolName</label>
<input id="SchoolName" name="SchoolName" type="text" value="" />
<input data-val="true" data-val-number="The field SchoolId must be a number." data-val-required="The SchoolId field is required." id="SchoolId" name="SchoolId" type="hidden" value="" />
<span class="field-validation-valid" data-valmsg-for="SchoolId" data-valmsg-replace="true"></span>
</p>
<p>
<input type="submit" />
</p>
</form>