I\'m an angular newbie, and I\'m stumbling over something in how angular\'s form validation directives work.
I know that I can fairly easily add directives to in
For me, beyond a feedback message, I needed define the field as invalid, preventing submit. So I gathered some approaches, like @thestewie approach, with a view configuration to gather a solution for dates comparison. I hope can aggregate the solutions that were presented.
The code is in PLUNKER
angular.module('MyApp')
.directive('thisEarlierThan', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, elem, attrs, ctrl) {
var startDate,
endDate;
scope.$watch(attrs.ngModel, function (newVal, oldVal, scope) {
startDate = newVal;
check();
});
scope.$watch(attrs.thisEarlierThan, function (newVal, oldVal, scope) {
endDate = newVal;
check();
});
var check = function () {
if (typeof startDate === 'undefined' || typeof endDate === 'undefined') {
return;
}
if (!validate(startDate)) {
startDate = new Date(startDate);
if (!validate(startDate)) {
return;
}
}
if (!validate(endDate)) {
endDate = new Date(endDate);
if (!validate(endDate)) {
return;
}
}
if (startDate < endDate) {
ctrl.$setValidity('thisEarlierThan', true);
}
else {
ctrl.$setValidity('thisEarlierThan', false);
}
return;
};
var validate = function (date) {
if (Object.prototype.toString.call(date) === '[object Date]') {
if (isNaN(date.getTime())) {
return false;
}
else {
return true;
}
}
else {
return false;
}
};
}
};
})
;