ng-messages asyncValidators

时间:2016-04-14 19:39:30

标签: angularjs ng-messages

我正在尝试编写指令来验证服务器上是否存在用户名。 如果它存在,我想通过ng-messages显示错误。 但由于某种原因,错误没有显示。我检查了服务器响应,它返回正确的值,但看起来像验证器无法解决承诺左右......

//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>

任何想法为什么它不起作用? 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

$ asyncValidators函数的返回需要是一个promise。拒绝承诺&#34;失败&#34;验证,承诺的决心&#34;通过&#34;验证。 工作小提琴here

&#13;
&#13;
var myApp = angular.module('myApp', ['ngMessages']);

myApp.controller('MyCtrl', ['$scope',
  function($scope) {}
]);

myApp.directive('checkIfUserExists', [
  '$q',
  '$http',
  function($q, $http) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attributes, ngModel) {
        ngModel.$asyncValidators.checkIfUserExists = function(modelValue) {
          var defer = $q.defer();
          $http.get(baseUrl + "/api/account/someone/" + user).then(function(isUnique) {
            if (response.data) {
              defer.resolve();
            } else {
              defer.reject();
            }
          }).catch(function(err) {
            // reject with the error message
            defer.reject(err);
          });
          // return the promise
          return defer.promise;
        };
      }
    };
  }
]);
&#13;
<section ng-controller="MyCtrl">
  <ng-form name="registerGeneralForm">
    <input type="text" check-if-user-exists id="username" name="username" ng-model="general.username" placeholder="******" />
    <div ng-messages="registerGeneralForm.username.$error" ng-show="registerGeneralForm.username.$dirty">
      <div ng-message="checkIfUserExists">Such user already exists</div>
    </div>
  </ng-form>
&#13;
&#13;
&#13;