Custom date format validation with jQuery datepick

2019-02-10 08:47发布

问题:

I'm almost there. I've created localized jQuery datepicker, added custom format validation, but can't get rid of (default?) US date format validation.

I'm rendering my date field like this:

...
@Html.EditorFor(m => m.JobDate)
@Html.ValidationMessageFor(m => m.JobDate)
...

and the HTML looks like this:

<input class="date hasDatepicker" data-val="true" data-val-required="The JobDate field is required." id="JobDate" name="JobDate" value="28.6.2011" type="text"> 
<span class="field-validation-valid" data-valmsg-for="JobDate" data-valmsg-replace="true"></span>

Finally, I hook up (in my javascript file) a jQuery datepicker control to handle my date field:

$(document).ready(function () {
   jQuery.validator.addMethod(
         "hrDateValidator",
         function(value, element) {
               try { jQuery.datepicker.parseDate( 'd.m.yy', value); return true; }
               catch(e){return false;}
            },
            "Datum nije u formatu d.m.gggg"
         );

   $('.date').datepicker({ dateFormat: "d.m.yy" });
   $.datepicker.setDefaults($.datepicker.regional["hr"]);
   $('.date').rules("remove");
   $('.date').rules("add", { hrDateValidator: true });      

});

However, now I have two validation rules active on the date field, the US date and this custom date.

I can't get rid of this US date rule, why doesn't this $('.date').rules("remove"); line remove the US date rule?

Thanks,

Igor

回答1:

You could try to "overwrite" the date validation method instead of adding a new one:

jQuery.validator.methods["date"] = function (value, element) { ... } 


回答2:

         date: function (value, element) {

            try { jQuery.datepicker.parseDate('d.m.yy', value); return true; }
            catch (e) { return false; }

        },