0

I'm using Angular Bootstrap UI Timepicker and if I enter 50 in the hours field, it highlights the field red, but nevertheless I get a valid date out of it that looks just like that Tue Nov 15 2016 05:00:55 GMT+0100.

Any ideas what I can do? Thanks!

molerat
  • 946
  • 4
  • 15
  • 43

1 Answers1

1

For that matter you could consider to limit the hour and minute input values, here is how to customize it for Timepicker

  1. introduce a custom template and specify the min, max and validate-value attributes for hour and minute input elements, for example:
<input type="text"  placeholder="HH" validate-value min="1" max="12" ng-model="hours" ng-change="updateHours()" class="form-control text-center" ng-readonly="::readonlyInput" maxlength="2" tabindex="{{::tabindex}}" ng-disabled="noIncrementHours()" ng-blur="blur()">
  1. implement validate-value directive to limit the number values in input element:
.directive('validateValue', function() {
   return {
       require: 'ngModel',
       link: function(scope, element, attrs, ngModelCtrl) {
            ngModelCtrl.$parsers.unshift(function(viewValue) {
                var min = Number(eval(attrs.min));
                var max = Number(eval(attrs.max));
                var value = Number(viewValue);
                var valid = (!isNaN(value) && value >= min && value <= max);

                if (!valid) { 
                    var currentValue = ngModelCtrl.$modelValue.toString();
                    ngModelCtrl.$setViewValue(currentValue);
                    ngModelCtrl.$render();
                    return currentValue;
                }
                else {
                    return viewValue;
                }
            });
      }
   };
})

Demo

metodribic
  • 1,561
  • 17
  • 27
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • Thanks, but is there no "native" way of doing it with simple bootstrap configuration? What you explain here will probably work. I will test it some day soon. – molerat Nov 18 '16 at 23:39
  • According to [settings page](https://angular-ui.github.io/bootstrap/) `max` and `min` could be specified to set maximum and minimum time a user can select but unfortunately those settings will not prevent the user from entering invalid values. – Vadim Gremyachev Nov 20 '16 at 17:24
  • So I did not try yours. I just console.logged the wrong time object. The result that comes straight from the timepicker seems to be null when invalid. Seems like I used another time object that has been modified before. Thanks anyway and sorry for the efforts. – molerat Dec 10 '16 at 22:11