I have a model with two of the properties set to required using annotations. How would I make the second property required only if the first property is a certain value? I have been able to make it work for a blank form using JQuery but the problem lies when I prepopulate the form with data, it doesnt recognize the value of the first property thus not not setting the other property required or not.
Here is what my View and Javascript are doing currently...
...
<div class="form-group">
@Html.LabelFor(x => x.Property1)
@Html.DropDownListFor(x => x.Property1, Model.Prop1Values, "", new {@class ="form-group prop1"})
@Html.ValidationMessageFor(x => x.Property1)
</div>
<div class="form-group">
@Html.LabelFor(x => x.PropDependentOnProp1)
@Html.DropDownListFor(x => x.PropDependentOnProp1, Model.Prop2Values, "", new {@class ="form-group prop2"})
@Html.ValidationMessageFor(x => x.PropDependentOnProp1)
</div>
...
<script>
$(".prop1").on("change", function() {
var selected = $(this).find(":selected").val();
if(selected == "Y"){
$(".prop2").rules('add', {
required: true
});
} else {
$(".prop2").rules('add', {
required: false
});
}
</script>
This works for a new form but when data is prefilled in the model, the validation change does not go into effect until Property1
is changed. I have tried to put similar logic to above in $(document).ready
but get "cant change undefined property 'settings'". I found a link to a possible workaround here to instantiate the validator first but this removes all validation for my other properties that need to be required and does not use the validation <span>
tags from the Html Helper methods.