2017-03-17 96 views
0

我目前使用选择选项来使用角度属性ng-repeat来收集信用卡过期日期的数据来生成月和年。我想在将它们连接成一个字符串之后返回月份和年份的值,并使用momentjs将字符串与今天的日期进行比较。当这样做时,月份和年份将作为无效日期返回。请参阅我下面的例子:

HTML

<select id="expMonth" class="form-control" ng-model="expMonth" ng-change="checkDate()"> 
    <option value="" disabled>Month</option> 
    <option value="{{ month }}" ng-repeat="month in months">{{ month }}</option> 
</select> 

<select id="expYear" class="form-control" ng-model="expYear" ng-change="checkDate()"> 
    <option value="" disabled>Year</option> 
    <option value="{{ year }}" ng-repeat="year in years">{{ year }}</option> 
</select> 

的JavaScript /角

$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; 
$scope.years = []; 
var currentYear = new Date().getFullYear(); 
for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push (i); 

$scope.checkDate = function() { 
    var expDate = $scope.expMonth.toString() + $scope.expYear.toString(); 
    if (expDate < moment().format('MMYYYY')) { 
     console.log('please enter an invalid date'); 
    } else { 
     console.log('this date is valid') 
    } 
} 

我相信日期返回一个字符串,我不知道如何将它转换,所以我可以比较它与今天的日期使用moment.format('MMYYYY')。任何帮助都是极好的。

回答

1

你试图比较一个字符串是否比另一个字符串不会工作。你有两个选择:

  1. 比较个月,并分别多年
  2. 使用片刻的isBefore方法比较的日期

独立的比较:

$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; 
$scope.years = []; 
var currentMonth = new Date().getMonth(); 
var currentYear = new Date().getFullYear(); 
for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i); 

$scope.checkDate = function() { 
    if (!($scope.expMonth && $scope.expYear)) return; 
    if ($scope.expMonth <= currentMonth && $scope.expYear <= currentYear) { 
    console.log('please enter an valid date'); 
    } else { 
    console.log('this date is valid'); 
    } 
} 

瞬间isBefore

$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; 
$scope.years = []; 
var currentMonth = new Date().getMonth(); 
var currentYear = new Date().getFullYear(); 
for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i); 

$scope.checkDate = function() { 
    if (!($scope.expMonth && $scope.expYear)) return; 
    var expDate = $scope.expMonth.toString() + $scope.expYear.toString(); 
    if (moment(expDate, 'MMYYYY').isBefore()) { 
    console.log('please enter an valid date'); 
    } else { 
    console.log('this date is valid'); 
    } 
} 
+0

这是完美的。我可以更改选择选项,并在控制台中没有无效日期消息的情况下获得预期结果。再次感谢! –