Angular UI日期选择器验证

时间:2017-05-01 01:50:16

标签: angularjs angular-ui-bootstrap angular-ui

In this plunk我有一个Angular UI日期选择器和一条消息,只有在日期有效时才会显示。问题是即使form.$valid为真,也始终显示消息。请注意,如果您输入有效或无效的日期,然后单击Validate,警报将正确显示日期有效或无效。

为什么验证消息始终显示,即使form.$valid为真?

的Javascript

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap']);

app.controller('ctl', function ($scope) {


    $scope.dtFrom = new Date ();

    $scope.config1 = {};
    $scope.config1.opened = false;
    $scope.open1 = function(event){
         event.preventDefault();
         event.stopPropagation();
         $scope.config1.opened = true;
    };

    $scope.validate = function(form){
        if (!form.$valid) {
           alert("Date invalid");
        }
        else {
           alert("Date valid");
        }
    }

});

HTML

<div ng-controller="ctl">
  <form name="form1" ng-submit="validate(form1)" novalidate>
      <p class="input-group" name="dtFrom" style="width:160px;margin-bottom:0px;">
          <input type="text" class="form-control" ng-model="dtFrom" 
               is-open="config1.opened"  uib-datepicker-popup="MM-dd-yyyy" 
               close-text="Close" />
           <span class="input-group-btn">
               <button type="button" class="btn btn-default" ng-click="open1($event)">
                  <i class="glyphicon glyphicon-calendar"></i>
               </button>
           </span>
      </p>
      <span ng-show="!form1.dtFrom.$valid">Invalid Date</span>
      <br/>
      <button type="submit">Validate</button>
  </form>
</div>

1 个答案:

答案 0 :(得分:3)

您应该为输入

创建名称
 <input type="text" class="form-control" ng-model="dtFrom" 
                   is-open="config1.opened"  uib-datepicker-popup="MM-dd-yyyy" 
                   close-text="Close" name="date" />
      <span ng-show="!form1.date.$valid">Invalid Date</span>

这是plnkr

http://plnkr.co/edit/gc0Oefhok6Gjim66UG0K?p=preview