Dri*_*bel 1 javascript validation http angularjs
我正在使用Angular 1.3.*,我尝试验证我的表单.它在ng-repeat内.所以我可能会获得几个输入字段.我不仅要求字段不为空,而且还要求从后端检索信息时搜索成功.
我有这个输入字段
<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>
Run Code Online (Sandbox Code Playgroud)
这是我对后端呼叫的尝试
.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)????
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,我希望用户存在.我想我必须使用asyncValidators进行后端调用.但是,我似乎没有得到它.对我来说,避免这种情况的一种方法是,在所有其他$错误而不是"必需"上,显示消息"似乎输入的用户不是有效输入".我怎样才能成功地进行后端呼叫并使用它,或者我怎样才能确保在所有其他场合显示其他错误消息?
小智 9
如果用户名存在,则只返回true,如果不存在,则直接拒绝该消息
.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');
});
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7456 次 |
| 最近记录: |