【问题标题】:How I restrict the user to only enter Date Field in angular bootstrap datepicker我如何限制用户仅在角度引导日期选择器中输入日期字段
【发布时间】:2015-03-20 15:23:58
【问题描述】:

我是角度方面的新手,我卡在无法限制用户手动输入有效日期的地方。它将日期设置为未定义的空字符以及用户输入的无效日期。我提到的日期格式是 MM-dd-yyyy。即使我输入 85/34/2102,它也会假定这是一个日期,并采用一些垃圾值,而不是验证并抛出错误。

我在 html 中的角度日期选择器代码

 <input type="text" class="form-control" datepicker-popup="{{clCtrl.format}}" 
   ng-model="clCtrl.QualityExpirationDate" is-open="clCtrl.openedQualityDate" 
   min-date="clCtrl.minDate" datepicker-options="clCtrl.dateOptions"  
   ng-required="true" close-on-date-selection="true" show-button-bar="false" />

和角度控制器端的代码

self.dateOptions = {
        formatYear: 'yy',
        startingDay: 1
    };

    self.formats = ['MM-dd-yyyy', 'MM/dd/yyyy', 'MM.dd.yyyy', 'shortDate'];
    self.format = self.formats[0]; 

self.openQualityDate = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();
        self.openedQualityDate = true;
    };


 self.toggleMin = function () {
        self.minDate = self.minDate ? null : new Date();
    };
    self.toggleMin();

    self.clear = function () {

        self.QualityExpirationDate = null;
    };

【问题讨论】:

    标签: angularjs html angular-ui


    【解决方案1】:

    向输入字段添加“只读”属性:

    <input type="text" readonly class="form-control" datepicker-popup="{{clCtrl.format}}" ng-model="clCtrl.QualityExpirationDate" is-open="clCtrl.openedQualityDate" min-date="clCtrl.minDate" datepicker-options="clCtrl.dateOptions" ng-required="true" close-on-date-selection="true" show-button-bar="false" />
    

    如果您想允许用户输入但限制为有效日期,您可以将其添加到您的控制器:

    $scope.$watch('dt', function(val) {
      $scope.isValidDate =  isNaN(new Date(val).getTime());
    });
    

    然后使用“isValidDate”范围属性来显示/隐藏消息和/或禁用提交,或任何您想做的事情。

    当然,最好将此验证抽象为指令,以便可以轻松地在所有日期字段中重复使用它。

    【讨论】:

    • 我们正在为用户提供便利,以便他手动输入日期以及从日历中选择。
    • 如果我们使用只读属性,则用户无法输入日期值,这里我们为用户提供了手动输入日期以及从日历中选择的便利。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2016-08-20
    • 2014-01-24
    相关资源
    最近更新 更多