使用$ http进行AngularJS自定义表单验证

时间:2013-05-29 10:01:24

标签: javascript angularjs angularjs-directive angularjs-scope

我的表格看起来像这样:

<form name="myForm" ng-submit="saveDeployment()">
    <input type="hidden" value="{{item.CloneUrl}}" name="cloneurl" />
    <input type="hidden" value="{{Username}}" name="username" />

    <input type="radio" name="deploymenttype" ng-model="item.deploymentType" value="azure" checked="checked">Azure 
    <br />
    <input type="radio" name="deploymenttype" ng-model="item.deploymentType" value="ftp">FTP

    <div id="azure" ng-show="item.deploymentType=='azure'">
        <label for="azurerepo">Azure Git Repo</label>
        <input type="text" name="azurerepo" ng-model="item.azurerepo" ng-class="{error: myForm.azurerepo.$invalid}" ng-required="item.deploymentType=='azure'" />
    </div>

    <div id="ftp" ng-show="item.deploymentType=='ftp'">
        <label for="ftpserver">FTP Server</label>
        <input type="text" name="ftpserver" ng-model="item.ftpserver" ng-class="{error: myForm.ftpserver.$invalid}" ng-required="item.deploymentType=='ftp'"  />

        <label for="ftppath">FTP Path</label>
        <input type="text" name="ftppath" ng-model="item.ftppath" ng-class="{error: myForm.ftppath.$invalid}" ng-required="item.deploymentType=='ftp'" />

        <label for="ftpusername">FTP Username</label>
        <input type="text" name="ftpusername" ng-model="item.ftpusername" ng-class="{error: myForm.ftpusername.$invalid}" ng-required="item.deploymentType=='ftp'"/>

        <label for="ftppassword">FTP Password</label>
        <input type="password" name="ftppassword" ng-model="item.ftppassword" ng-class="{error: myForm.ftppassword.$invalid}" ng-required="item.deploymentType=='ftp'"/>
    </div>

    <input type="submit" value="Save" ng-disabled="myForm.$invalid"/>

</form>

它的设置使得输入数据后所需的字段和保存按钮都可以正常工作。但是,我的部分验证将是"Is the user already registered?",我将使用输入的数据通过POST使用$ http命中服务器。

我应该将这个逻辑放在saveDeployment()函数中还是有更好的地方放置它?

*的 更新: *

我已经实现了以下作为元素的属性应用但是它在我不喜欢的每个按键上调用服务器/数据库:

 app.directive('repoAvailable', function ($http, $timeout) { // available
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ctrl) {
                console.log(ctrl);
                ctrl.$parsers.push(function (viewValue) {
                    // set it to true here, otherwise it will not 
                    // clear out when previous validators fail.
                    ctrl.$setValidity('repoAvailable', true);
                    if (ctrl.$valid) {
                        // set it to false here, because if we need to check 
                        // the validity of the email, it's invalid until the 
                        // AJAX responds.
                        ctrl.$setValidity('checkingRepo', false);

                        // now do your thing, chicken wing.
                        if (viewValue !== "" && typeof viewValue !== "undefined") {
                            $http.post('http://localhost:12008/alreadyregistered',viewValue) //set to 'Test.json' for it to return true.
                                .success(function (data, status, headers, config) {
                                    ctrl.$setValidity('repoAvailable', true);
                                    ctrl.$setValidity('checkingRepo', true);
                                })
                                .error(function (data, status, headers, config) {
                                    ctrl.$setValidity('repoAvailable', false);
                                    ctrl.$setValidity('checkingRepo', true);
                                });
                        } else {
                            ctrl.$setValidity('repoAvailable', false);
                            ctrl.$setValidity('checkingRepo', true);
                        }
                    }
                    return viewValue;
                });

            }
        };
    });

3 个答案:

答案 0 :(得分:1)

你不需要在指令中发出$ http请求,更好的地方是控制器。

您可以在控制器内指定方法 - $scope.saveDeployment = function () { // here you make and handle your error on request ... };您将错误保存到范围,然后创建一个指示$scope.yourResponseObject并根据它设置有效性的指令。

此外,如果您需要输入字段模糊等请求和错误之类的内容,则需要使用elem.bind('blur', ...)创建一个简单的指令,并使用回调调用$scope.saveDeployment来处理有效性。

看看这些例子,可能会有类似的东西 - https://github.com/angular/angular.js/wiki/JsFiddle-Examples

答案 1 :(得分:1)

使用异步$http ajax调用验证表单输入字段是一种常见的需求,但我还没有发现任何完整,可重用且易于使用的实现,所以我尽我所能之一。

此功能对于检查用户名,电子邮件或其他字段/列是否唯一非常有用,但是还有很多其他用例必须使用ajax调用验证值(如示例所示)。 / p>

我的解决方案具有以下功能:

  • 接受&#34;检查&#34; $scope进行$http调用或任何类型验证(同步或异步)的函数
  • 接受一个&#34;门&#34;来自$scope的函数,允许根据值或ngModel状态绕过检查。
  • 去除&#34;检查&#34;功能的执行直到用户停止输入
  • 确保仅使用最新的$http调用结果(如果多个被触发并返回乱序)。
  • 允许状态绑定,以便UI可以适当方便地做出响应。
  • 可自定义的去抖时间,检查/门功能,绑定名称和验证名称。

我的指示是pmkr-validate-custom (GitHub)。它可以用于任何异步验证。我已经在几个版本中测试了它,早在1.1.5

以下是Twitter Bootstrap的示例用法,其中我检查用户名是否唯一。

Live Demo

<form name="the_form" class="form-group has-feedback">
  <div ng-class="{'has-success':userNameUnique.valid, 'has-warning':userNameUnique.invalid}">
    <label for="user_name">Username</label>
    <input 
      name="user_name" 
      ng-model="user.userName" 
      pmkr-validate-custom="{name:'unique', fn:checkUserNameUnique, gate:gateUserNameUnique, wait:500, props:'userNameUnique'}" 
      pmkr-pristine-original="" 
      class="form-control"
    >
    <span ng-show="userNameUnique.valid" class="glyphicon glyphicon-ok form-control-feedback"></span>
    <span ng-show="userNameUnique.invalid" class="glyphicon glyphicon-warning-sign form-control-feedback"></span>
    <i ng-show="userNameUnique.pending" class="glyphicon glyphicon-refresh fa-spin form-control-feedback"></i>
    <p ng-show="userNameUnique.valid" class="alert alert-success">"{{userNameUnique.checkedValue}}" is availiable.</p>
    <p ng-show="userNameUnique.invalid" class="alert alert-warning">"{{userNameUnique.checkedValue}}" is not availiable.</p>
    <button 
      ng-disabled="the_form.$invalid || the_form.user_name.$pristine || userNameUnique.pending" 
      class="btn btn-default"
    >Submit</button>
  </div>
</form>

样本控制器:

// Note that this ought to be in a service and referenced to $scope. This is just for demonstration.
$scope.checkUserNameUnique = function(value) {
  return $http.get(validationUrl+value).then(function(resp) {
    // use resp to determine if value valid
    return isValid; // true or false
  });
}

// The directive is gated off when this function returns true.
$scope.gateUserNameUnique = function(value, $ngModel) {
  return !value || $ngModel.$pristine;
};

如果我做了任何改进,它们将在GitHub上更新,但我也会在此处为此指令及其依赖项(可能不会更新)添加代码。我欢迎提出建议或问题GitHub issues

angular.module('pmkr.validateCustom', [
  'pmkr.debounce'
])

.directive('pmkrValidateCustom', [
  '$q',
  'pmkr.debounce',
  function($q, debounce) {

    var directive = {
      restrict: 'A',
      require: 'ngModel',
      // set priority so that other directives can change ngModel state ($pristine, etc) before gate function
      priority: 1,
      link: function($scope, $element, $attrs, $ngModel) {

        var opts = $scope.$eval($attrs.pmkrValidateCustom);

        // this reference is used as a convenience for $scope[opts.props]
        var props = {
          pending : false,
          validating : false,
          checkedValue : null,
          valid : null,
          invalid : null
        };
        // if opts.props is set, assign props to $scope
        opts.props && ($scope[opts.props] = props);

        // debounce validation function
        var debouncedFn = debounce(validate, opts.wait);
        var latestFn = debounce.latest(debouncedFn);

        // initially valid
        $ngModel.$setValidity(opts.name, true);

        // track gated state
        var gate;

        $scope.$watch(function() {
          return $ngModel.$viewValue;
        }, valueChange);

        // set model validity and props based on gated state
        function setValidity(isValid) {
          $ngModel.$setValidity(opts.name, isValid);
          if (gate) {
            props.valid = props.invalid = null;
          } else {
            props.valid = !(props.invalid = !isValid);
          }
        }

        function validate(val) {
          if (gate) { return; }
          props.validating = true;
          return opts.fn(val);
        }

        function valueChange(val) {

          if (opts.gate && (gate = opts.gate(val, $ngModel))) {
            props.pending = props.validating = false;
            setValidity(true);
            return;
          }

          props.pending = true;
          props.valid = props.invalid = null;

          latestFn(val).then(function(isValid) {
            if (gate) { return; }
            props.checkedValue = val;
            setValidity(isValid);
            props.pending = props.validating = false;
          });

        }

      } // link

    }; // directive

    return directive;

  }
])

;

angular.module('pmkr.debounce', [])

.factory('pmkr.debounce', [
  '$timeout',
  '$q',
  function($timeout, $q) {

    var service = function() {
      return debounceFactory.apply(this, arguments);
    };
    service.immediate = function() {
      return debounceImmediateFactory.apply(this, arguments);
    };
    service.latest = function() {
      return debounceLatestFactory.apply(this, arguments);
    };

    function debounceFactory(fn, wait) {

      var timeoutPromise;

      function debounced() {

        var deferred = $q.defer();

        var context = this;
        var args = arguments;

        $timeout.cancel(timeoutPromise);

        timeoutPromise = $timeout(function() {
          deferred.resolve(fn.apply(context, args));
        }, wait);

        return deferred.promise;

      }

      return debounced;

    }

    function debounceImmediateFactory(fn, wait) {

      var timeoutPromise;

      function debounced() {

        var deferred = $q.defer();

        var context = this;
        var args = arguments;

        if (!timeoutPromise) {
          deferred.resolve(fn.apply(context, args));
          // return here?
        }

        $timeout.cancel(timeoutPromise);
        timeoutPromise = $timeout(function() {
          timeoutPromise = null;
        }, wait);

        return deferred.promise;

      }

      return debounced;

    }

    function debounceLatestFactory(fn) {

      var latestArgs;

      function debounced() {

        var args = latestArgs = JSON.stringify(arguments);

        var deferred = $q.defer();

        fn.apply(this, arguments).then(function(res) {
          if (latestArgs === args) {
            deferred.resolve(res);
          }
        }, function(res) {
          if (latestArgs === args) {
            deferred.reject(res);
          }
        });

        return deferred.promise;

      }

      return debounced;

    }

    return service;

  }
])

;

angular.module('pmkr.pristineOriginal', [])

.directive('pmkrPristineOriginal', [
  function() {

    var directive = {
      restrict : 'A',
      require : 'ngModel',
      link: function($scope, $element, $atts, $ngModel) {

        var pristineVal = null;

        $scope.$watch(function() {
          return $ngModel.$viewValue;
        }, function(val) {
          // set pristineVal to newVal the first time this function runs
          if (pristineVal === null) {
            pristineVal = $ngModel.$isEmpty(val) ? '' : val.toString();
          }

          // newVal is the original value - set input to pristine state
          if (pristineVal === val) {
            $ngModel.$setPristine();
          }

        });

      }
    };

    return directive;

  }
])

;

答案 2 :(得分:0)

我的解决方案取自Kosmetika的想法。

我使用了angular-ui项目并在控制器上设置了onBlur回调,该回调通过$http调用了网络服务。

这将控制器/模型属性设置为true或false。

然后我使用<span>使用ng-show来监视控制器/模型属性,这样当Web服务返回时它会显示用户信息