My custom validation directive is functioning properly, but it relies on another field's value to determine if the first field is valid. The second field happens to be a select list.
I am curious if there is a way to manually trigger validation when the second field is changed, possibly using the ng-change
event. How should I go about handling this situation?
This is the code for my directive:
angular.module('myApp', []).
directive('validage', function () {
return {
require: 'ngModel',
link: function (scope, elem, attr, ngModel) {
function validate(value) {
var valid = true;
if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
&& scope.dep.DependantType == "Spouse") {
valid = false;
}
ngModel.$setValidity('validage', valid);
return value;
}
//For DOM -> model validation
ngModel.$parsers.unshift(function (value) {
var valid = true;
if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
&& scope.dep.DependantType == "Spouse") {
valid = false;
}
ngModel.$setValidity('validage', valid);
return value;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function (value) {
var valid = true;
if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
&& scope.dep.DependantType == "Spouse") {
valid = false;
}
ngModel.$setValidity('validage', valid);
return value;
});
}
};
});
If you're unfamiliar with AngularJS, I suggest checking out these two informative articles: part 1 and part 2. These provide an overview of AngularJS forms.