Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom date format validation with jQuery datepicker (can't get rid of US date validation)

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

like image 225
igorludi Avatar asked Jun 28 '11 11:06

igorludi


2 Answers

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

jQuery.validator.methods["date"] = function (value, element) { ... } 
like image 129
Tz_ Avatar answered Nov 17 '22 22:11

Tz_


         date: function (value, element) {

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

        },
like image 36
Haddar Macdasi Avatar answered Nov 17 '22 23:11

Haddar Macdasi