My current project involves an Angular 1.5.3 app.
This is the task at hand:
I have a user form with two date input fields. I need to implement custom validation on the form so that if the "expiry date" is greater than the "effective date", an error message is displayed to the user.
I believe I can achieve this by creating a custom directive and utilizing ng-messages.
Below is a snippet of my code:
<form name="form.mainForm">
<div>
<span>Effective Date: </span>
<input required type="date" name="effectiveDate" ng-model="effectiveDate" />
<div>
<span>Expiry Date: </span>
<input
type="date"
name="expiryDate"
ng-model="expiryDate"
date-greater-than="{{ effectiveDate }}" />
</div>
</div>
</form>
app.directive('dateGreaterThan', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: false,
link: function (scope, elm, attrs, ctrl) {
console.log(' here we are ');
function isValidDateRange(expiryDate, effectiveDate) {
console.log(expiryDate, effectiveDate);
if (effectiveDate == null || expiryDate == null ) {
return true;
}
return effectiveDate > expiryDate;
}
function validateDateRange(inputValue) {
var expiryDate = inputValue;
var effectiveDate = scope.effectiveDate;
var isValid = isValidDateRange(expiryDate, effectiveDate);
console.log("isValid: ", isValid);
ctrl.$setValidity('dateGreaterThan', isValid);
return inputValue;
}
ctrl.$parsers.unshift(validateDateRange);
ctrl.$formatters.push(validateDateRange);
attrs.$observe('dateGreaterThan', function () {
validateDateRange(ctrl.$viewValue);
});
}
};
I've made an attempt to address this issue, but unfortunately, my directive is not functioning as expected. It does not update when the dates change and it does not integrate well with ng-messages.
Here is my attempt: http://jsfiddle.net/aubz88/q7n3abre/