despite using google and so, I didn't find a solution to my problem. Thank you for taking a look.
I want to implement the following input validation behaviour (using angular ngModelController):
Input validation should only be triggered after the user first leaves the field. However if there are validation errors, the validation should trigger not only on blur, but also on change, so that the user is imediately notified, when the error is corrected.
I created a directive with only a (post)link function, that "require"s ngModel on the same element.
angular.module('foo').directive('errFB', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElem, attrs, ngModel){
// which trigger source / event should I listen on?
// iElem.on, ngModel.$viewChange, scope.$on, scope.$parent.$on?
// iElem.on, seemed the best fit.
xyz.on(..., function(){
if (ngModel.$touched && ngModel.$invalid){
// here validation is not triggered.
// probably, due to having ngModelOptions
// set to only validate on blur?
// could this be changed programmatically?
ngModel.$validate();
}
}
}
}
});
for the second comment regarding triggering validation: I considered doing it the other way round: i.e. first enabling validation via ngModelOptions on both 'default' (change) and 'blur' and then stopping the validation from running in case it's caused by the 'default' trigger, when ngModel.$touched === false. But disabling validation seems to be very difficult and going against the flow of angular.
Any kind of suggestions are appreciated. Thank you very much!
So, after some long hard trying, I found a way. Actually it's quite simple:
link: function(scope, iElem, attrs, ngModel){
iElem.on("change", function(evt){
if (ngModel.$touched && ngModel.$invalid){
ngModel.$options.updateOnDefault = true;
ngModel.$validate();
}
});
As you can see the model.$options (which define the events on which the modelController's $validators pipeline is executed) can be set after creation/initiation time. The call to validate will queue a validation (which will execute on the next validation event).
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