0

I have a date field that is required only if a text field has a value and vice versa.

Since it's conditional I can't just use the required attribute on the C# class, ie.

[Required(ErrorMessage = "*")]

So for the onChange event of both fields I run this function:

function validateTermination()
{
    if ($('#TerminationDate').val() == null && $('#TerminationReason').val() == null)
    {
        //remove validation
        $('#TerminationDate').rules('remove');
        $('#TerminationReason').rules('remove');
    }
    else
    {
        //add validation
        $('#TerminationDate').rules('add', { required: true });
        $('#TerminationReason').rules('add', { required: true });
    }
}

Both of the add rule statements cause the error to throw. The error occurs in the jquery.validate.js file here:

var settings = $.data(element.form, "validator").settings;

I guess $.data(element.form, "validator") is null for some reason, although I'm at a loss as to why.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Legion
  • 3,922
  • 8
  • 51
  • 95
  • 1
    JSYK, you can create a custom validation attribute when a requirement is conditional. – quiqs Apr 17 '19 at 00:12
  • I think the answer for conditional validation you are looking for is here https://stackoverflow.com/questions/2417113/asp-net-mvc-conditional-validation – godfathr Apr 17 '19 at 03:26
  • @godfathr That doesn't work on client side. – Legion Apr 17 '19 at 15:05
  • @quiqs I've seen posts about that but they never work client side. – Legion Apr 17 '19 at 15:05
  • @Legion The marked answer doesn't work client side, but the thread contains another answer using Expressive annotations that does. It's the third answer down. https://github.com/jwaliszko/ExpressiveAnnotations – godfathr Apr 18 '19 at 16:10
  • @godfathr OK, I had seen Expressive Annotations before and it looks promising. I'm apprehensive about using it though since this is a large legacy application and I have concerns about something breaking if I bring it in. I was hoping to find a way to use jQuery's validator component since ASP MVC already uses it and just modify the validation rules client side as needed. – Legion Apr 18 '19 at 16:27

0 Answers0