Home > OS >  jQuery validation isn't work after make fields hidden and then visible
jQuery validation isn't work after make fields hidden and then visible

Time:05-02

I'm trying to implement conditional form validation. On loading, I make all fields with the specified class hidden and depending on the selected type and classes for the block remove the hidden property.

<form>
<div >
    <label for="typeId" >Type</label>
    <select id="typeId"
        name="typeId"
        asp-for="typeId"
        asp-items="@Model.TypeListItems"
        
        data-val-required="A Type is required"
        required></select>
    <span  asp-validation-for="typeId"></span>
</div>
                    
<div >
    <label for="details" >If so, please provide details.</label>
    <textarea rows="3"  name="details" asp-for="details"></textarea>
    <span  asp-validation-for="details"></span>
</div>

<div >
    <label for="myfield1" >If so, please provide details.</label>
    <textarea rows="3"  name="myfield1" asp-for="myfield1"></textarea>
    <span  asp-validation-for="myfield1"></span>
</div>

<div >
    <label for="myfield2" >If so, please provide details.</label>
    <textarea rows="3"  name="myfield2" asp-for="myfield2"></textarea>
    <span  asp-validation-for="myfield2"></span>
</div>
<input type="submit" />
</form>

The JavaScript on document ready:

function onChangeType() {
    hideConditionFields();

    var type = document.getElementById("typeId");
    setupConditionFields(type);
}

function setupConditionFields(type) {
    var css = typeCss[type.value];
    $(".fields").find(css.divClass)
        .each(function (i) {
            $(this).prop("hidden", false);
        });
}

function hideConditionFields() {
    $(".fields").find(".condition-field")
        .each(function (i) {
            $(this).prop("hidden", true);
         });
}

So in the first will be called hideConditionFields() to hide all conditional fields, and then will be shown specified for chosen type fields. If I comment hideConditionFields method's calling - validation works, but my approach doesn't. What do I need to do after hiding and unhiding fields jQuery validation on such fields will continue working?

CodePudding user response:

If - as I suppose - you're using the enter image description here

In the above code, it is using asp-validation-summary="All", if you want to show the validation message based on the model, change it to

<div asp-validation-summary="ModelOnly" ></div>.

  • Related