I have the following directive which I put on input fields that use the angular-ui-bootstrap datepicker:
angular.module('directives.validators.date', [])
.directive('validDate',[ '$filter', function ($filter) {
return {
restrict:'A',
require:'ngModel',
link: function (scope, el, attrs, ngModel) {
var pattern = /^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/;
ngModel.scope = scope;
ngModel.attrs = attrs;
el.on('blur',function() {
if(typeof ngModel.$viewValue === "object"){
var str = $filter('date')(ngModel.$viewValue, "dd.MM.yyyy");
ngModel.$setViewValue(str);
}
if(ngModel.$viewValue){
if(ngModel.$viewValue!=="" && !pattern.test(ngModel.$viewValue)){
ngModel.$setValidity("date",false);
}
}
});
scope.$watch(function () {
return ngModel.$modelValue;
},
function() {
if(ngModel.$pristine){ //if the data has just been fetched, convert it to date format.
if (typeof ngModel.$viewValue === "number"){
var date = new Date(ngModel.$viewValue);
//var str = $filter('date')(date, "dd.MM.yyyy");
ngModel.$setViewValue(date);
ngModel.$setPristine(true);
var formName = $("form")[0].name;
ngModel.scope[formName].$setPristine(true);
ngModel.$setValidity("date",true);
}
}
if(ngModel.$viewValue){ //when the filed is changed, if it is corrected set that the date is valid
if(ngModel.$viewValue==="" || pattern.test(ngModel.$viewValue)){
ngModel.$setValidity("date",true);
}
}
});
}
};
}]);
I had a problem with the datepicker component that my form wouldn't submit if the datepicker field wasn't touched (even if it had data in it, e.g. when I would edit a resource). It basically counted the form as invalid even though a good date was submitted. This directive fixed that, but when I upgraded my angular to 1.3 the directive no longer works.
What would I need to change to get this directive to work again?