ASP.NET MVC4 - Hidden field validation not clearing after value is set

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>

Answers


The reason the error message remains is because there are none of the normal validation triggers on a hidden field. Normally, for a single field, validation is triggered on key-up or on blur. The field is hidden so only the submit button will trigger a validation test of the hidden field when the whole form is validated.

However, you can programatically trigger a validation test on any field by calling the .valid() method at any time.

$('input[name="field"]').valid();  // force validation of 'input name="field"'

Here is a crude jsFiddle demo: http://jsfiddle.net/LJzfu/

  • Click 'submit' to show the "required" message on the hidden input called field2, which has no value.

  • Clicking the "go" button programatically puts a value in the hidden input. The form would now technically pass validation (upon submit) but the error message remains because we have no validation trigger.

  • Trigger validation by calling .valid() immediately after putting a value in the hidden field. This forces a validation test of the hidden field, which then hides the error message (as long as the validation rules are satisfied).


Need Your Help

Custom validation method that accesses other model properties

c# asp.net-mvc entity-framework validation

I'm attempting to create a custom validation method for one of my entities, so I've created a class that inherits from ValidationAttribute:

PDO beginTransaction Not Letting Script Execute

php pdo transactions

I have a PHP script using PDO Transactions.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.