0

I have implemented a dropdown DateTime control and validators based on the accepted answer in the following topic: How to validate a date using 3 dropdowns( day, month, year ) using jquery unobtrusive validation?

I am using MVC 4.

This 3-dropdown date works fine mostly, but sometimes when I click those three dropdowns and choose different values (including "unselected" values), I get the error message form default DateTime validator "The field Date of birth must be a date." even if I have selected valid year/month/date and my custom validator passes.

This message does not prevent POSTing the form when the date is set correctly, but the message is confusing for users.

When I inspect the unobtrusive rules in Firebug, I see that this message comes form default "date" rule. I know I could use rules( "remove" (or delete rule, message) to remove this default date rule, but I am not sure, when it is appropriate time to remove them to stop MVC adding that rule back again.

How do I remove this default "date" rule to ensure that only my custom rule is effective for these three dropdowns?

Community
  • 1
  • 1
JustAMartin
  • 13,165
  • 18
  • 99
  • 183

2 Answers2

1

I haven't tried this but I guess the default datatype client validation rules are added by the ClientDataTypeModelValidatorProvider. This provider is ON by default. You can try removing that from the ModelValidatorProvidersCollection in Global.asax.cs.

  var clientDataTypeProvider = ModelValidatorProviders.Providers.FirstOrDefault(p => p.GetType().Equals(typeof(ClientDataTypeModelValidatorProvider)));
  ModelValidatorProviders.Providers.Remove(clientDataTypeProvider);

Note: By removing this you will lose the validation for number as well. Other option is create a custom ClientDataTypeModelValidatorProvider and add it into the providers collection. One more thing is this idea works at a global level and affect all the other places.

VJAI
  • 32,167
  • 23
  • 102
  • 164
0

So I invented a quick hack, maybe someone will find it useful or maybe have something to improve:

function removeDefaultDateValidators(selector, validatorToRemove) {
    $('form').each(function () {
        var settings = $(this).validate().settings;
        $(selector, this).each(function () {
            // rules and messages seem to be keyed by element name, not id
            var elmName = $(this).attr('name');
            delete settings.rules[elmName][validatorToRemove];
            delete settings.messages[elmName][validatorToRemove];
        });
    });
}

$(function () {
    removeDefaultDateValidators('select[data-val-trippleddldate]', 'date');
});

When page is loaded, it iterates through all the forms and finds the elements which should have the validator removed. In my case I am removing default date validator form all the dropdowns which have my custom trippleddldate validator.

Tested in Firefox and IE 9, "works on my machine".

JustAMartin
  • 13,165
  • 18
  • 99
  • 183