【问题标题】:AngularJS form custom validation (future date)AngularJS 表单自定义验证(未来日期)
【发布时间】:2015-04-21 13:42:37
【问题描述】:

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

例如:

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

我想添加一个自定义规则来验证日期是否在未来而不是过去。

【问题讨论】:

    标签: javascript angularjs date


    【解决方案1】:

    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.
    

    【讨论】:

    • @pixelbits- 你能为此分享一个 jsfiddle 吗?
    • 当然,希望这会有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    相关资源
    最近更新 更多