I'm trying to write directive to validate if username exists on the server. If it exists I want to show error via ng-messages. But for some reason the error doesn't show.I checked server response and it returns right values but looks like validator cannot resolve promise or so...
//Directive
angular.module('main').directive('checkIfUserExists', checkIfUserExists);
checkIfUserExists.$inject = ['authService'];
function checkIfUserExists(authService) {
return {
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$asyncValidators.checkIfUserExists = function (modelValue) {
return authService.suchUserAlreadyExists(modelValue);
};
}
};
};
//service method
suchUserAlreadyExists: function (user) {
return $http.get(baseUrl + "/api/account/someone/" + user).then(function (response, status, headers, config) {
console.log(response.data);
return !response.data;
},function (data, status, headers, config) {
return $q.reject('error occured');
});
}
//Input I want to validate
<div class="col-md-6">
<div class="row">
<div class="col-md-8">
<input type="text" check-if-user-exists ng-pattern="/^[a-zA-Z0-9]*$/" ng-maxlength="10" ng-minlength="6" class="form-control" id="username" name="username" ng-model="general.username" placeholder="******" required />
</div>
</div>
<div class="row">
<div class="col-md-12 inputErrorMessage">
<div ng-messages="registerGeneralForm.username.$error" ng-if="registerGeneralForm.username.$dirty">
<div ng-message="required">This field is required</div>
<div ng-message="pattern">Only alphanumeric characters allowed</div>
<div ng-message="maxlength">Username cannot exceed 10 characters</div>
<div ng-message="minlength">Username must be over 6 characters</div>
<div ng-message="checkIfUserExists">Such user already exists</div>
</div>
</div>
</div>
</div>
Any ideas why it doesn't work? Thank you for any help