I have two date inputs to track the start and end of a trip. I want to write a custom validator to make sure the end date is within X days of the start date.
I have already written a single validator to check future dates, but I don't know if it's possible to create a validator that is dependant on another field? From my understanding ngModel gives me access to the current model variable, but is there a way to get access to other variables?
<input type="date" future-date name="startDate" ng-model="startDate" required />
<div ng-messages="form.startDate.$error">
<p ng-message="required">Please select a start date</p>
<p ng-message="futureDate">Must be in future</p>
</div>
<input type="date" future-date name="endDate" ng-model="endDate" required />
<div ng-messages="form.endDate.$error">
<p ng-message="required">Please select a start date</p>
<p ng-message="futureDate">Must be in future</p>
</div>
and the directive:
(function(){
'use strict';
angular
.module('app')
.directive('futureDate', autocomplete);
function autocomplete() {
return {
restrict: 'A',
require : 'ngModel',
link: function(scope, element, attrs, ngModel) {
var validator = function(date) {
if(!date || date.length === 0) return;
var valid = (new Date() > now);
ngModel.$setValidity('futureDate', valid);
return date;
};
ngModel.$parsers.push(validator);
}
};
}
})();