Angularjs开始日期和结束日期验证 [英] Angularjs start date and end date validations

查看:579
本文介绍了Angularjs开始日期和结束日期验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全新的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


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

  2. 在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/

    这篇关于Angularjs开始日期和结束日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆