diff --git a/src/components/datepicker/js/datepickerDirective.js b/src/components/datepicker/js/datepickerDirective.js index 050e69771f..b663193dcc 100644 --- a/src/components/datepicker/js/datepickerDirective.js +++ b/src/components/datepicker/js/datepickerDirective.js @@ -607,9 +607,31 @@ this.ngModelCtrl.$setValidity('valid', date == null); } + var input = this.inputElement.value; + var parsedDate = this.locale.parseDate(input); + + if (!this.isInputValid(input, parsedDate) && this.ngModelCtrl.$valid) { + this.ngModelCtrl.$setValidity('valid', date == null); + } + angular.element(this.inputContainer).toggleClass(INVALID_CLASS, !this.ngModelCtrl.$valid); }; + /** + * Check to see if the input is valid as the validation should fail if the model is invalid + * + * @param {String} inputString + * @param {Date} parsedDate + * @return {boolean} Whether the input is valid + */ + DatePickerCtrl.prototype.isInputValid = function (inputString, parsedDate) { + return inputString == '' || ( + this.dateUtil.isValidDate(parsedDate) && + this.locale.isDateComplete(inputString) && + this.isDateEnabled(parsedDate) + ); + }; + /** Clears any error flags set by `updateErrorState`. */ DatePickerCtrl.prototype.clearErrorState = function() { this.inputContainer.classList.remove(INVALID_CLASS); @@ -634,11 +656,7 @@ // An input string is valid if it is either empty (representing no date) // or if it parses to a valid date that the user is allowed to select. - var isValidInput = inputString == '' || ( - this.dateUtil.isValidDate(parsedDate) && - this.locale.isDateComplete(inputString) && - this.isDateEnabled(parsedDate) - ); + var isValidInput = this.isInputValid(inputString, parsedDate); // The datepicker's model is only updated when there is a valid input. if (isValidInput) { diff --git a/src/components/datepicker/js/datepickerDirective.spec.js b/src/components/datepicker/js/datepickerDirective.spec.js index 38b045b479..7019cc17d2 100644 --- a/src/components/datepicker/js/datepickerDirective.spec.js +++ b/src/components/datepicker/js/datepickerDirective.spec.js @@ -344,6 +344,16 @@ describe('md-datepicker', function() { expect(controller.ngModelCtrl.$error['mindate']).toBe(true); }); + it('should apply ngMessages errors when the date becomes invalid from keyboard input', function() { + populateInputElement('5/30/2012'); + pageScope.$apply(); + expect(controller.ngModelCtrl.$error['valid']).toBeFalsy(); + + populateInputElement('5/30/2012z'); + pageScope.$apply(); + expect(controller.ngModelCtrl.$error['valid']).toBeTruthy(); + }); + it('should evaluate ngChange expression when date changes from keyboard input', function() { populateInputElement('2/14/1976');