简体   繁体   中英

AngularJS form custom validation (future date)

I am trying to add validation to my AngularJS app and 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?

For example:

<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 if it is in the future and not in the past.

Demo Plunker

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>

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()];
});

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);
}

You can then use AngularJS form validation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM