我正在尝试一个简单的angular日期验证,其中当选择的日期大于当前日期时,todate会在提交时显示错误消息。但是输出不符合预期。选择任何日期都会出错,但条件是在调试断点处正确检查。

链接]:plunker

这是代码:

$scope.form1submit=function(date){

        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd='0'+dd
        }

        if(mm<10) {
            mm='0'+mm
        }

        todayDate = mm+'/'+dd+'/'+yyyy;
        console.log(todayDate);
        var toDate = date.toDate;
        var toDatelength = date.toDate.length;


        if(toDate > todayDate && toDatelength > 0){

            $scope.form1.todate.$setValidity("todateerror", false);

        }else{
            $scope.form1.todate.$setValidity("todateerror", true);
        }
        };




<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://www.jqueryscript.net/demo/Simple-Date-Picker-For-jQuery-AngularJS-Datepicker/"></script>
<span class="">
        <label class="">to date</label>
        <input id="toDate" name="todate" type="text" class=""
               ng-model-options="{allowInvalid: true}"
               placeholder="To Date"
               data-datepicker="{theme: 'flat'}"
               ng-model="date.toDate"
               ng-disabled="date.fromdate"
               ng-required="date.fromdate" />
       <span ng-show="form1.$submitted && form1.todate.$error">

           <div ng-message="todateerror" class="">To date is more than todays date</div>
       </span>
</span>

最佳答案

Here我已修复您的代码。


1)您不应该将日期作为字符串进行比较。
2)您必须使用form1.todate.$error代替form1.todate.$error.todateerror

关于javascript - $ setvalidity不根据指定条件设置错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41546592/

10-11 08:51