Using Angular JS version 1.5.6, I am looking to implement asynchronous input validation that occurs only on blur. However, I am unable to use modelOption: {debounce: 500} or modelOption: {updateOn: 'blur'} due to the directive being used with other directives.
I attempted the code below, but encountered a situation where no async validation is performed on the first blur, and subsequently, every typed character triggers the async validation, which is not the intended behavior.
function blurFocusDirective($http, $q) {
return {
require: 'ngModel',
link: function(scope, elm, attrs, modelCtrl) {
elm.on('blur', function() {
console.log('capture blur event');
modelCtrl.$asyncValidators.myValidator = function(modelValue, viewValue) {
return $http.get('/username-check/' + modelValue).then(
function(response) {
if (!response.data.validUsername) {
return $q.reject(response.data.errorMessage);
}
return true;
}
);
};
});
}
};
}
To observe the issue in action, you can check the following Plunker link. Press F12 to view the console log for more insights.
Note that the endpoint '/username-check/' is fictional and unrelated to the actual issue at hand. The problem lies in the fact that the async HTTP request fires on each typed character instead of just during blur.