2

In this plunk I have an Angular UI date picker and a message that should be shown only when the date is valid. The problem is that the message is always shown, even when form.$valid is true. Note that if you enter a valid or invalid date and then click on Validate, an alert will display correctly that the date is valid or invalid respectively.

Why is the validation message shown all the time, even when form.$valid is true?

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 Answer 1

4

You should create name for the input

 <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>

Here is plnkr

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

Sign up to request clarification or add additional context in comments.

2 Comments

the name of the field is dtFrom, why did you change it to date ? using dtFrom with your solution doesn't work, see here plnkr.co/edit/aGyLQccXIuQxO6QKb4Hv?p=preview
@ps0604 name of input not name of ptag . see here plnkr.co/edit/OHuJ2FxP0YCFjTivsIqH?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.