I have a custom validation directive that is being called properly when one field is changed. However, whether this field is valid is also based on another field's value. This second field is a select list if that is of importance.
I was wondering if there was some way I could trigger validation manually when the second form is changed. Perhaps by using the ng-change
event. What is the proper way to handle something like this?
Here is 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 new to AngularJS, I would definitely recommend reading these 2 articles: part 1 & part 2. They are an overview of AngularJS forms.
After searching a lot for this I've found that we can trigger validation simply by calling $validate()
on the desired field.
So for example if your form is named my_form (i.e. in the markup the form tag has a name="my_form"
attribute) and the name of the field you want to validate is date (in the markup the input field has a name="date"
attribute), then as you suggested you can use the ng-change
event of the second field and call $scope.my_form.date.$validate();
whenever the ng-change function is invoked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With