Search code examples
jqueryasp.net-mvcdata-annotations

In MVC 5, How do I remove the required attribute depending on another dropdown value?


Currently, the form is working as intended until you submit the form with the Usage_Status dropdown selection with value a of '2' and then switch to any other value and submit again. The javascript validation message 'The Assigned User field is required.' appears and does not go away after switching values on the dropdown and submitting again. Is it possible to remove the required attribute, or set it on the condition that '2' is selected?

HTML:

<div class="row">
        <div class="form-group col-sm-4">
            @Html.LabelFor(model => model.Usage_Status, new { @class = "control-label col-md-12" })
            <div class="col-md-10">
                @Html.DropDownList("Usage_Status", new SelectList(statuses, "ID", "Name"), new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Usage_Status)
            </div>
        </div>

        <div class="form-group col-sm-4">
            @Html.LabelFor(model => model.Assigned_User, new { @class = "control-label col-md-12" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Assigned_User, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Assigned_User)
            </div>
        </div>

        <div class="form-group col-sm-4">
            @Html.LabelFor(model => model.Department, new { @class = "control-label col-md-12" })
            <div class="col-md-10">
                @Html.DropDownList("Department", new SelectList(departments, "ID", "Name"), string.Empty, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Department)
            </div>
        </div>
    </div>

JavaScript:

$(document).ready(function () {
$('#Usage_Status').change(function (e) {
    //If item is being used, require a user and department. Otherwise, disabled those fields.
    if ($('#Usage_Status').val() == "2") {
        $('#Assigned_User').rules('add', 'required');
        $('#Assigned_User').removeAttr('disabled');
    } else {
        $('#Assigned_User').rules('remove', 'required');
        $('#Assigned_User').removeAttr('required');
        $('#Assigned_User').attr('disabled', 'disabled');
    }

});

Solution

  • If you're doing conditional validation, e.g one field's value in your form defines validation for another field you need an additional library. I use expressive annotations