Trigger validation of a field when another field is changed
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.
I had a similar problem: two form fields "interval" (for $scope.monitor.interval) and "timeout" (for $scope.monitor.timeout) with the condition that timeout must not exceed half of interval.
First, I added a custom validator to timeout that checks for this condition. Now I needed to trigger the timeout validator also when interval changes. I achieved this by watching the monitor.interval property of the model:
function EditMonitorCtrl($scope, $log, dialog, monitor) { $scope.monitor = monitor; ... // trigger validation of timeout field when interval changes $scope.$watch("monitor.interval", function() { if ($scope.editMonitorDlg.timeout.$viewValue) { $scope.editMonitorDlg.timeout.$setViewValue($scope.editMonitorDlg.timeout.$viewValue); } });}
Without "if" the timeout value got removed during intialisation of the dialog.
I was unable to get ng-blur="myForm.myField.$validate()"
working in AngularJS 1.5, possibly because the model for myField
was empty.
However, ng-blur="myForm.myField.$setTouched()"
did work.