Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  39] [ 5]  / answers: 1 / hits: 7874  / 10 Years ago, tue, january 13, 2015, 12:00:00

I am using Angular 1.3.* and I try to validate my form. It is within a ng-repeat. So I may obtain several input fields. I do not only require the field to be not empty, but also require the search to be successful when retrieving information from the backend.



I have this input field



                               <input type=text
ng-model=user
placeholder=username
name=user{{$index}}
typeahead=data as data.name for data in getUser($viewValue)
typeahead-editable=false
class=form-control
autocomplete=off
userValidator
required>
<div ng-if=myForm.$submitted ng-messages=myForm.user{{$index}}.$error >
<div ng-message=required>You need to type something</div>
</div>

<div ng-if=myForm.$submitted ng-messages=myForm.user{{$index}}.$error>
<div ng-message=userValidator> It seems that the entered user is not a valid input</div>
</div>


here is my try for the backendCall



  .directive('userValidator',function($http,$q){
return{
require:'ngModel',
link:function($scope,element,attrs,ngModel){
ngModel.$asyncValidators.userAvailable=function(userInput){
return $http.post('/user'+userInput)
.then(function)????

}
}
}
});


Note, that I WANT the user to exist. I guess I'll have to make a backend call with asyncValidators. However, I do not seem to get it. A way for me to circumvent this would be to say that on ALL other $errors than required, show the message It seems that the entered user is not a valid input. How could I do a successful backend call and use it or alternatively, how can I make sure to show the other error message on all other occasions?


More From » angularjs

 Answers
4

If the username exists then simply return true, if it does not exists simply reject with the message



.directive('userValidator',function($http,$q){
return{
require:'ngModel',
link:function($scope,element,attrs,ngModel){
ngModel.$asyncValidators.userAvailable = function(modelValue , viewValue) {

var userInput= modelValue || viewValue;
return $http.post('/user'+userInput)
.then(function() {
//username exists, this means validation success
return true;
}, function() {
//username does not exist, therefore this validation fails
return $q.reject('selected username does not exists');
});

}
}
}
});

[#40032] Monday, January 12, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dewayneh

Total Points: 538
Total Questions: 114
Total Answers: 97

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
;