针对同一验证器共享多个字段的验证状态

时间:2015-08-27 13:46:15

标签: angularjs angularjs-directive angularjs-validation

我将首先说明我搜索过google和SO,但我没有找到针对这种特定情况的答案。是的,还有其他帖子听起来相同,但更多的是基于“MoreThan / LessThan”的心态。这根本不遵循这种心态,所以请不要将其标记为重复引用它们。

查看Plunker Example

我正在尝试确保用户没有输入页面上已存在的地址。为此,我需要验证所有地址字段,因为不同的位置可能具有相同的街道地址。如果地址被修复为不重复,我需要验证器将所有相关字段设置为有效(如果有效字段无效)。目前,它仅将最后修改的字段设置为有效,并将其余字段设置为无效。

Plunker example演示了正在发生的事情。我已经尝试了许多不同的方法,例如遍历所有字段并将它们设置为prestine和untouched,然后将它们设置为脏并触摸以再次触发验证,但我没有运气使其工作。

验证

   angular.directive('ruleFunc', ['$parse', function($parse) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function($scope, $element, $attrs, $ngModel) {
        var validatorName = $attrs.ruleName;
        var validatorFunc = $attrs.ruleFunc;

        if (!angular.isDefined(validatorName)) {
          throw Error("rule-name attribute must be defined.");
        }

        if (!angular.isDefined(validatorFunc)) {
          throw Error("rule-func attribute must be defined.");
        }

        // in real code I passing a function call with the model as the param
        // this example demonstrated the issue I am having though
        var expressionHandler = $parse(validatorFunc);

        // had to use viewChangeListener because changes to the model 
        // were not showing up correctly in the actual implementation
        $ngModel.$viewChangeListeners.push(function() {
          var valid = expressionHandler($scope);
          $ngModel.$setValidity(validatorName, valid);
        });
      });

表格

<form name="AddressForm" novalidate>
<h1>Address Form</h1>
<div style="margin:20px">
  <input id="Street" type="text" name="Street" placeholder="Street" data-ng-model="ctrl.address.street" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.Street.$error.profileHasContact}}
  <br />

  <input id="City" type="text" name="City" placeholder="City" data-ng-model="ctrl.address.city" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.City.$error.profileHasContact}}
  <br />

  <input id="State" type="text" name="State" placeholder="State" data-ng-model="ctrl.address.state" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.State.$error.profileHasContact}}
  <br />

  <input id="Zip" type="text" name="Zip" placeholder="Zip" data-ng-model="ctrl.address.zip" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.Zip.$error.profileHasContact}}
  <br />

  <div ng-if="(AddressForm.Street.$error.profileHasContact 
         || AddressForm.City.$error.profileHasContact 
         || AddressForm.State.$error.profileHasContact
         || AddressForm.Zip.$error.profileHasContact)">Address already exists in Main Contacts</div>

  <button type="submit">Submit</button>
</div>

1 个答案:

答案 0 :(得分:0)

我确实发现了一篇足够接近我可以破解解决方案的帖子。 Form validation - Required one of many in a group

以下是更新后的plunker

更新了验证工具

directive('ruleFunc', ['$parse', function($parse) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function($scope, $element, $attrs, $ngModel) {
        var validatorName = $attrs.ruleName;
        var validatorFunc = $attrs.ruleFunc;
        var groupName = $attrs.ruleGroup;

        if (!angular.isDefined(validatorName)) {
          throw Error("rule-name attribute must be defined.");
        }

        if (!angular.isDefined(validatorFunc)) {
          throw Error("rule-func attribute must be defined.");
        }

        if(angular.isDefined(groupName)){

          // setup place to store groups if needed
          if (!$scope.__ruleValidationGroups) {
              $scope.__ruleValidationGroups = {};
          }
          var groups = $scope.__ruleValidationGroups;

          // setip group if needed
          if(!groups[groupName]){
            groups[groupName] = {};
          }
          var group = groups[groupName];

          // assign model to group
          group[$attrs.ngModel] = {
            model: $ngModel
          }
        }

        function updateValidity(valid){
          if(angular.isDefined(groupName)){

            // set all models in group to same validity
            for(var prop in group){
              if(group.hasOwnProperty(prop)){
                group[prop].model.$setValidity(validatorName, valid);
              }
            }

          }
          else
          {
            // set this model validity if not in group
            $ngModel.$setValidity(validatorName, valid);
          }
        }

        var expressionHandler = $parse(validatorFunc);
        $ngModel.$viewChangeListeners.push(function() {
          var valid = expressionHandler($scope);
          updateValidity(valid);
        });
      }
    };
  }]);