Karl Fazer
Karl Fazer

Reputation: 57

How to deal with "ng-model value must be a Date object" error in console

Angular ui-datepicker on use of the 'Clear' button sets the input to a null value, this generates in the dev-tools console the error

Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.

There are SO questions about the wheres and whys but I want to handle the error in my own code, without hacking the datepicker plugin itself. It isn't causing my form to behave wrongly, as I handle the validation. I am using this code:

function logicalDates(from, to) {
    if (vm.to === null || vm.to === undefined || vm.to === NaN) {
        vm.logicalDatesBool = true;
    } else {
        if (new Date(vm.from) > new Date(vm.to)) {
            vm.logicalDatesBool = false;
        } else {
            vm.logicalDatesBool = true;
        }
    }
}

One of the two datepickers looks like this, the other is the same except it has "to" instead of "from" and is numbered "ng-click="open2..."

<input class="form-control"
   type="text"
   ng-click="open1($event,'opened1')" 
   is-open="opened1"
   max-date="maxDate"
   placeholder="{{'dd/mm/yyyy' | translate}}"
   datepicker-options="dateOptions"
   ng-required="false"
   datepicker-popup="{{format}}"
   ng-model="vm.from"
   current-text="{{'Today'| translate}}"
   toggle-weeks-text="{{'Weeks'| translate}}"
   clear-text="{{'Clear'| translate}}"
   close-text="{{'Close'| translate}}"
   ng-change="vm.logicalDates(vm.from, vm.to)" />
<span class="input-group-btn">
<button class="btn btn-standard" ng-click="open1($event)">
    <i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
<div class="value form-group pull-left" ng-if="!vm.logicalDatesBool" 
style="margin-left: 2rem;" >
<div class="note note-error" translate>'From' date should preceed 'to' 
date</div>
</div>   

I think this is a question about error handling, but I'm not sure! I tried using $datepickerSuppressError on the input element, but it did not work.

How can I handle the console error above?

Upvotes: 2

Views: 3956

Answers (1)

Andrew Adam
Andrew Adam

Reputation: 1582

as advised in the following thread (namely this comment) there is an existing workaround by modifying datepicker.js line 652:

ngModel.$viewChangeListeners.push(function () {
    if (ngModel.$viewValue) 
        scope.date = dateParser.parse(ngModel.$viewValue, dateFormat, scope.date) || 
            new Date(ngModel.$viewValue);
    else
        scope.date = null;
});

In a previous experience of mine it did work although it was quite some time ago and I am also not 100% sure about the version you are using and I used back then.

Edit

After discussing in case of no access to datepicker.js another comment from the same thread might help you out.

Upvotes: 1

Related Questions