Angularjs开始日期和结束日期验证日期、结束、Angularjs

2023-09-13 04:15:52 作者:[凉了时光乱了心]

我完全新的Angularjs并试图验证2场景。我有2个一个文本框与起始日期和其他与结束日期。我检查

I am completely New to Angularjs and trying to validate 2 scenarios. I have 2 text boxes one with start date and the other with end date. I am checking

在UI显示验证错误,如果开始日期不大于或等于今天。它应该是今天或以后的今天,任何一天在UI显示验证错误,如果开始日期是不是结束日期。结束日期应该大于开始日期。

我试过低于code,没有工作。任何建议请。

I tried the below code which did not work. Any suggestions please.

HTML code

Html Code

<label for="endDate" class="control-label">Start Date:</label>
<div>
    <input type="text" class="form-control" 
           id="startDate" ng-model="startDate" />
</div>

<label for="text" class="control-label">End Date:</label>
<div>
    <input type="text" class="form-control" 
           id="endDate" ng-model="endDate" 
            ng-change='checkErr(startDate,endDate)' />

</div>

<span>{{errMessage}}</span>

JS code

js code

$scope.checkErr = function(startDate,endDate){
    $scope.errMessage = '';
    $scope.curDate = new Date();

    if(startDate < endDate){
      $scope.errMessage = 'End Date should be greate than start date';
      return false;
    }
    if(startDate < curDate){
       $scope.errMessage = 'Start date should not be before today.';
       return false;
    }

  };

我输入类型文本为日期controls.I现在用引导日期选择器。

推荐答案

您已经扭转在第一位的逻辑,你必须从构建一个的startDate新的日期来比较今天的日期。你也设置为CURDATE范围, $ scope.curDate =新的日期()但随后你被引用为 CURDATE 没有 $范围所以这是不确定的。最后,你需要投 stateDate 结束日期来的日期为好。否则,你只是比较字符串。

You have the logic reversed on the first bit and you have to construct a new date from startDate to compare to today's date. Also you set curDate to the scope, $scope.curDate = new Date() but then you were referencing it as curDate without the $scope so it was undefined. Lastly, you need to cast stateDate and endDate to a date as well. Otherwise you're just comparing strings.

$scope.checkErr = function(startDate,endDate) {
    $scope.errMessage = '';
    var curDate = new Date();

    if(new Date(startDate) > new Date(endDate)){
      $scope.errMessage = 'End Date should be greater than start date';
      return false;
    }
    if(new Date(startDate) < curDate){
       $scope.errMessage = 'Start date should not be before today.';
       return false;
    }
};

的例子: http://jsfiddle.net/peceLm14/