【问题标题】:Share validation state for multiple fields against the same validator针对同一个验证器共享多个字段的验证状态
【发布时间】:2023-04-09 21:18:01
【问题描述】:

我将首先说明我已经搜索了 google 和 SO,但我还没有找到针对这种特定情况的答案。是的,还有其他的帖子听起来一样,但更多的是基于“MoreThan / LessThan”的心态。这根本不符合这种心态,因此请不要将其标记为引用它们的重复项。

查看Plunker Example

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

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

验证器

   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>

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-validation


    【解决方案1】:

    我确实找到了一个足够接近的帖子,我可以拼凑出一个解决方案。 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);
            });
          }
        };
      }]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2011-01-31
      相关资源
      最近更新 更多