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 class="mb-3">
<label for="typeId" class="form-label">Type</label>
<select id="typeId"
name="typeId"
asp-for="typeId"
asp-items="@Model.TypeListItems"
class="form-select"
data-val-required="A Type is required"
required></select>
<span class="text-danger validation-message" asp-validation-for="typeId"></span>
</div>
<div class="mb-3 condition-field field1 field2">
<label for="details" class="form-label">If so, please provide details.</label>
<textarea rows="3" class="form-control dependsField" name="details" asp-for="details"></textarea>
<span class="text-danger validation-message" asp-validation-for="details"></span>
</div>
<div class="mb-3 condition-field field1">
<label for="myfield1" class="form-label">If so, please provide details.</label>
<textarea rows="3" class="form-control dependsField" name="myfield1" asp-for="myfield1"></textarea>
<span class="text-danger validation-message" asp-validation-for="myfield1"></span>
</div>
<div class="mb-3 condition-field field2">
<label for="myfield2" class="form-label">If so, please provide details.</label>
<textarea rows="3" class="form-control dependsField" name="myfield2" asp-for="myfield2"></textarea>
<span class="text-danger validation-message" 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?