2017-03-02 42 views
1

嗨,我在一个项目中,我至今领域工作。如何比较两个日期有验证功能

我需要验证的同一领域。

1)应允许用户选择以前的日期或一年。 2)但不允许用户选择未来的日期。

我用下面的代码,它仅用于本年度工作正常。 任何人都可以帮助我实现它。

$scope.$watch('date', function(val) { 
    var dateNewOnCreatessssss = $scope.convertedTimeToSend(new Date()); 
    console.log("dateNewOnCreatessssss", dateNewOnCreatessssss); 
    $scope.convertedTimeToSend = function(timestamp) { 
    var c = moment(timestamp).format("MM-DD-YYYY"); 
    return c; 
    }; 
    if (val) { 
    $scope.dateErrorMsg = false; 
    } 
    var dateNewOnCreatessssssll = $scope.convertedTimeToSend(val); 
    console.log("dateNewOnCreatessssssll", dateNewOnCreatessssssll); 
    if (dateNewOnCreatessssssll > dateNewOnCreatessssss) { 
    $scope.dateErrorMsgsssssss = true; 
    $scope.newReceiptSaveBtn = "true"; 
    } else { 
    $scope.dateErrorMsgsssssss = false; 
    $scope.newReceiptSaveBtn = "false"; 
    } 
}); 

回答

2

好吧m8,你的代码是一团糟。只要使用momentjs提供的所有好东西来使其工作。 Finaly这个功能看起来应该像这样简单的片断:

$scope.$watch('date', function(val) { 
    if (val) { 

     //Init 
     var today = new moment(); 
     var selectedDate = new moment(val); 

     if(selectedDate.isBefore(today)){ 
      $scope.dateErrorMsg = false; 
      $scope.newReceiptSaveBtn = "false"; 

     } else { 
      $scope.dateErrorMsg = true; 
      $scope.newReceiptSaveBtn = "true"; 
     } 
    } 
}); 

虽然上面的例子中的重点是基于你的代码的解决方案。它会好得多,营造一个纯粹AngularJS处理像这样的方法:

var myApp = angular.module('myApp',[]); 
 

 
myApp.controller('MyCtrl', function ($scope) { 
 

 
    //Init 
 
    $scope.date = new moment()._d; 
 
    $scope.error = false; 
 
    
 
    $scope.validateDate = function() { 
 
    
 
     //Init 
 
     var today = new moment(); 
 
     var selectedDate = new moment($scope.date); 
 
     
 
     if(selectedDate.isBefore(today)){ 
 
      $scope.error = false; 
 
     } else { 
 
      $scope.error = true; 
 
     } 
 
    } 
 
});
.error { 
 
    border:1px solid red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> 
 

 
<div ng-app="myApp"> 
 
    <div ng-controller="MyCtrl"> 
 
    <input type="date" 
 
      ng-model="date" 
 
      ng-change="validateDate()" 
 
      ng-class="{ 'error': error }" /> 
 
    </div> 
 
</div>

+0

感谢您的回答@lin .. :) – User123

+0

@ User123乐意帮忙。 – lin

+0

我很抱歉地说,但我无法继续进行26-03-2016。出错。你能帮我关于这个 – User123