验证表单中的异常 AngularJS 行为禁止选择应该接受的日期

abnormal angularjs behaviour in validation forms forbid to pick a date that should be accepted

本文关键字:选择 禁止 该接受 日期 表单 异常 AngularJS 验证      更新时间:2023-09-26

我想使用 angularjs 验证日期输入,我遇到了一种似乎想要的行为,但我并不真正理解它的目标。

当您选择一个无效的日期(因为它不存在,或者因为它超出了所需范围)时,ng-model 后面的字段将被销毁。

这是一个显示问题的flickr:链接到plnkr

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Example - example-date-input-directive-production</title>   
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>
  </head>
  <body ng-app="dateInputExample">
    <script>
      angular.module('dateInputExample', []).controller('DateController', ['$scope', function($scope) {
        $scope.add=function(){
          $scope.example = {value: new Date(2016, 0, 15)};
        }
        $scope.add();
      }]);
    </script>
    <form name="myForm" ng-controller="DateController as dateCtrl">
      <label for="exampleInput">pick a date out of range (2016-01-15 : 2016-02-10) or that does not exist :</label>
      <input ng-show="example.value" type="date" id="exampleInput" name="input" ng-model="example.value" placeholder="yyyy-MM-dd" min="2016-01-15" max="2016-02-10" required />
      <div role="alert">
        <button ng-show="!example.value" ng-click="add()">add the date</button>
      </div>
      <tt>value = {{example.value ? example.value  : "example.value has been destroyed"}}</tt><br/>
    </form>
  </body>
</html>

我的问题如下:

这种行为是正常的还是错误?

如果这是正常行为,在前面的示例中,我如何选择应该是接受范围内的日期的 2016-02-05。

在此示例中,使用此行为,我无法选择二月的日期。

实际上对我来说,它确实看起来像一个错误,至少对于日期验证器来说。也许在其他情况下可以预料到,但这就是我们在这里看到的:

1)正常行为 - 如果我们删除最小/最大验证并尝试设置不正确的日期 - 它会重置为正确的日期,值不会消失。

2)添加最小/最大验证器,尝试将日期设置为超出范围 - 它会重置为空。预期:它重置为以前的正确值(就像在"正常行为"情况下一样)

解决方法是创建自定义指令以将日期值保持在给定范围内。该指令的本质是一个$watch,它检查日期是否在范围内并在必要时修复它:

scope.$watch(attr.ngModel, function(newValue) {
  if (minVal) {
    valid = !isValidDate(newValue) || angular.isUndefined(minVal) || parseDate(newValue) >= minVal;
    if (!valid) {
      // If date is less than min - set it to min
      // scope.example.value = minVal;
      ctrl.$setViewValue(attr.minDate);
      ctrl.$render();
    }
  }
  if (maxVal) {
    valid = !isValidDate(newValue) || angular.isUndefined(maxVal) || parseDate(newValue) <= maxVal;
    if (!valid) {
      // If date is greater than max - set it to max
      // scope.example.value = maxVal;
      ctrl.$setViewValue(attr.maxDate);
      ctrl.$render();
    }
  }
});

这是一个带有演示的 plunker。