User can type invalid date into AngularUI Datepicker

时间:2016-04-21 22:36:14

标签: javascript angularjs twitter-bootstrap angularjs-directive datepicker

I am having a problem where in the AngularUI Bootstrap Datepicker I have a min date and a max date. If you open the popup, you can't click on the disabled dates. However you are able to type in a date outside of the range. I want it to bring it to the min date if the typed date is below and the max date if the typed date is later.

Here is the plunker: http://plnkr.co/edit/6U4YdTIyFXjOqRJm2qTq?p=preview

In the controller:

$scope.dateOptions = {
    maxDate: $scope.maxDate,
    minDate: $scope.minDate,
};

In the template: datepicker-options="dateOptions"

I'd like to avoid using jQuery or a date library unless necessary, since this is the only field where I need this functionality.

If it helps, I have found some reports of this issue, however they are marked as "fixed" so maybe I am missing something.

https://github.com/angular-ui/bootstrap/pull/2901

https://github.com/angular-ui/bootstrap/pull/3020

The similar stackflow question

AngularUI datepicker allows typing value outside of range actually has a working plunker but it isn't angularui datepicker, and the accepted answer suggests a plug-in, which I want to avoid. I did try using ui-date="dateOptions" in my template the same as the plunker but nothing changed.

I am thinking of some sort of directive like so:

angular.module('ui.bootstrap.demo').directive('isValidDate', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {

        //first, assume it's a valid date until check
        ctrl.$setValidity('isValidDate', true);

        if(scope.dt > attrs.maxDate || scope.dt < attrs.minDate) {
            ctrl.$setValidity('isValidDate', false);
        }
    }
};
});

and adding is-valid-date to the template. However, this is not working :(

1 个答案:

答案 0 :(得分:2)

我已经指示为你工作了,让我知道这个解决方案适合你:Plukr url here

angular.module('ui.bootstrap.demo').directive('isValidDate', function() {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
     scope.invalidDateChoosen= false;
    elem.bind("change", function(){  
    ctrl.$setValidity('isValidDate', true);
      if(scope.dt > scope.mymaxmonth || scope.dt < scope.mymindate) {
        scope.dt='';
        scope.invalidDateChoosen=true;
        ctrl.$setValidity('isValidDate', false);
        scope.$apply();
      }
    });
}

}; });