javascript - $asyncValidators Angular

标签 javascript angularjs validation http

我正在使用 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>

这是我对 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)????

        }
      }
    }
  });

请注意,我希望用户存在。我想我必须使用 asyncValidators 进行后端调用。但是,我似乎不明白。我规避这种情况的一种方法是说,在除“必需”之外的所有其他 $errors 上,显示消息“似乎输入的用户不是有效输入”。我怎样才能成功进行后端调用并使用它,或者,我怎样才能确保在所有其他情况下显示其他错误消息?

最佳答案

如果用户名存在则返回真,如果不存在则拒绝

.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');
         });

      }
    }
  }
});

关于javascript - $asyncValidators Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923529/

相关文章:

javascript - 检查div不在叠加层后面时是否可见div

javascript - 第二次单击时表行更新。表单验证 JavaScript

javascript - 如何防止 AngularJS 在 $resource 操作中对 GET 请求中的参数进行排序?

javascript - 如何调整页脚位置 html css

javascript - 使用 AngularJS 方法绑定(bind)防止重复调用

javascript - ng-重复不起作用

javascript - 为什么 AngularUI Bootstrap 日期选择器没有弹出?

forms - Spring MVC 选择 :selected after form validation error 形式的值

javascript - 最喜欢的 Web 表单验证技术

javascript - 页面加载后如何加载数据表?