如何使用AngularJS验证datepicker范围?

时间:2015-06-09 14:04:34

标签: javascript angularjs kendo-ui

我正在尝试验证日期,因此在下面的html结束日期应始终大于开始日期,我使用了k-min和k-rebind,这对用户来说是禁用开始日期的数字,但是使用该实现的用户可以返回并选择更高的开始日期,所以在这里我实现AngularJS自定义验证,如果结束日期小于开始日期抛出验证错误,但它没有用下面的代码...

main.html中

<div class="form-group col-md-6 fieldHeight">
    <label for="cycleStart" class="col-md-4 required">Cycle Start</label>
    <div class="col-md-8">
        <input kendo-date-picker
        type="text" class="form-control" id="cycleStart"
        name="cycleStart"
        ng-model="rcsaCycleDTO.cycStartDate" 
        k-ng-model="cycleStrtObj"
        onkeydown="return false;"
        ng-change="validateDate()"
        required data-required-msg="Cycle start is required">
        <p class="text-danger" ng-show="createRcsaCycleForm.cycleStart.$touched && createRcsaCycleForm.cycleStart.$error.required">Cycle Start is required field</p>                                
    </div>
<div class="form-group col-md-6 fieldHeight">
    <label for="cycleEnd" class="col-md-4 required">Cycle end (due date)</label>
    <div class="col-md-8">
        <input 
        kendo-date-picker
        type="text" class="form-control" id="cycleEnd"
        name="cycleEnd"
        ng-model="rcsaCycleDTO.cycEndDate"
        k-min="cycleStrtObj" 
        k-rebind="cycleStrtObj"
        onkeydown="return false;"
        ng-change="validateDate()"
        required>
        <p class="text-danger" ng-show="createRcsaCycleForm.cycleEnd.$touched && createRcsaCycleForm.cycleEnd.$error.required">Cycle End is required field</p>
        <p class="text-danger" ng-show="createRcsaCycleForm.cycleEnd.$error.valid"> Name already existed</p>
    </div>
</div>

main.js

$scope.validateDate = function(){
          var startDate = $scope.rcsaCycleDTO.cycStartDate;
          var endDate = $scope.rcsaCycleDTO.cycEndDate;
          if (endDate <= startDate) {
            $scope.createRcsaCycleForm.cycleEnd.$setValidity('valid',false);
          }
        }

1 个答案:

答案 0 :(得分:0)

尝试使用Date.parse,然后比较日期。

    $scope.validateDate = function(){
      var startDate = Date.parse($scope.rcsaCycleDTO.cycStartDate);
      var endDate = Date.parse($scope.rcsaCycleDTO.cycEndDate);
      if (stateDate > endDate) {
        $scope.createRcsaCycleForm.rcsaName.$setValidity('valid',false);
      }
    }