Angularjs表单自定义验证 - 未来的日期自定义、表单、日期、未来

2023-09-13 03:33:29 作者:沉寂丶冷夏

我想验证添加到我的angular.js程序,我想测试一个特定的日期是在未来。什么是这样做的最佳做法,如果我有2选择这个?

I am trying to add a validation to my angular.js app I want to test if a specific date is in the future. what is the best practice to do so if I have 2 selects for this?

为前:

            <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>

我想添加自定义的规则来验证日期是在将来,而不是过去。

I want to add a custom rule to validate the date is in the future and not in the past.

推荐答案

演示Plunker

您可以创建依赖于自定义指令 ngModel

You can create a custom directive that relies on 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和可选父窗体:

The directive would create an isolated scope to create a private scope, and require ngModel and an optional parent form:

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

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

The directive's controller would initialize years and months for the drop down lists:

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']        
}

该指令会使下面的模板:

The directive would render the following template:

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>'

设置 $观看来设定日期只要一个月或一年下拉的变化:

Set up a $watch to set the date whenever the month or year drop-down changes:

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验证:

Use the ngModel controller to add a futureDate validator:

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

您可以再使用AngularJS表单验证:

You can then use AngularJS form validation:

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