1

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.

Talon
  • 811
  • 7
  • 22
  • Use a `[RequiredIf]` conditional validation attribute. There are plenty of example of the web, and there are libraries such as [foolproof](https://github.com/leniel/foolproof) that you can use. Do not attempt to change the validator to add/remove rules if using mvc's client side validation (and in any case, you must always validate on the server - client side validation should only be consider s nice bonus - anyonw can override it) –  May 10 '18 at 21:46
  • And if you want to write your own conditional validation attributes, refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  May 10 '18 at 21:48

1 Answers1

0

You can implement your own validation attribute and access the model using validation context. The following code is from dotnetmentors and should give you a good idea of how to modify it for your needs

using System.ComponentModel.DataAnnotations;

namespace FirstMVC.Models
{
    public class ValidLastDeliveryDate : ValidationAttribute
    {
        protected override ValidationResult 
                IsValid(object value, ValidationContext validationContext)
        {
            var model = (Models.Customer)validationContext.ObjectInstance;
            DateTime _lastDeliveryDate = Convert.ToDateTime(value);
            DateTime _dateJoin = Convert.ToDateTime(model.JoinDate);  

            if (_dateJoin > _lastDeliveryDate)
            {
                return new ValidationResult
                    ("Last Delivery Date can not be less than Join date.");                
            }
            else if (_lastDeliveryDate > DateTime.Now)
            {
                return new ValidationResult
                    ("Last Delivery Date can not be greater than current date.");                
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }
}
Braydie
  • 716
  • 9
  • 27
  • Just realised that you might be looking for a jQuery solution rather than c#... My answer might not be that helpful.. – Braydie May 10 '18 at 19:06