AngularJS表单自定义验证(未来日期)

时间:2015-04-21 13:42:37

标签: javascript angularjs date

我正在尝试为我的AngularJS应用添加验证,并且我想测试某个特定日期是否在将来。如果我有两个选择,这样做的最佳做法是什么?

例如:

<select name="expirationYear"
   ng-model="expYear"
   required>
   <option ng-repeat="n in [] | range:21" value="{{currentYear+n}}">{{currentYear+n}}</option>
</select>

<select name="expirationMonth"
   ng-model="expMotnh"
   required>
   <option ng-repeat="n in [] | range:12" value="{{n+1}}">{{n+1}}</option>
</select>

我想添加一个自定义规则来验证日期,如果它在将来而不是过去。

1 个答案:

答案 0 :(得分:4)

Demo Plunker

您可以创建依赖ngModel

的自定义指令
<form name="form"> 
  <date-picker name="date" ng-model="date"></date-picker> 
  <span class="error" ng-show="form.date.$error.futureDate">
       Error: Date is in the future!
  </span>
</form>

该指令将创建一个独立的范围来创建一个私有范围,并需要ngModel和一个可选的父窗体:

require: ['ngModel', '^?form'],
scope: { }

该指令的控制器将初始化下拉列表的年份和月份:

controller: function($scope){
   $scope.years = [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018];
   $scope.months = ['Jan','Feb', 'Mar', 'Apr', 'May','Jun', 'Jul','Aug', 'Sep', 'Oct','Nov','Dec']        
}

该指令将呈现以下模板:

template: '<select ng-model="year" ng-options="y for y in years"></select>' 
        + '<select ng-model="month" ng-options ="m for m in months"></select>'

设置$watch以在月份或年份下拉列表更改时设置日期:

scope.$watch('year', function(year) {
  if (year) {
      var month = scope.months.indexOf(scope.month);
      ngModel.$setViewValue(new Date(year, month,1));
  }
});
scope.$watch('month', function(month) {
  if (month) {
      var year = scope.year;
      var monthIndex = scope.months.indexOf(scope.month);
      ngModel.$setViewValue(new Date(year, monthIndex,1));
  }
});
ngModel.$formatters.push(function(val) {
  scope.year = val.getFullYear();
  scope.month = scope.months[val.getMonth()];
});

使用ngModel控制器添加futureDate验证器:

ngModel.$validators.futureDate = function(val) {
  var date = new Date();
  return val <= new Date(date.getFullYear(), date.getMonth(),1);
}

然后,您可以使用AngularJS表单验证:

if ($scope.form.date.$valid) {
     ...
}
if ($scope.form.date.$error.futureDate) {
     ...
}
etc.