当浏览器自动填充表单字段时,$ parsers \ $ formatters函数不会触发

时间:2013-12-10 10:32:45

标签: javascript google-chrome angularjs

我的应用程序中有一个自定义验证指令(下面附带代码)。 问题是,当需要一个或多个表单字段并且chrome自动填充它们时,字段将保持无效,直到用户手动更改它们。 我怀疑这种情况发生的原因是镀铬会在角度甚至引导之前填充场地。

有没有办法解决这个问题?。

代码:

app.directive('myValidate', function($timeout, $filter) {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
              var validator = function(viewValue){
                var viewValueStr = viewValue + '';
                scope.valid = true;
                scope.fieldName = attrs.name;
                var nameStr = attrs.name + '';
                if(!attrs.displayName || attrs.displayName.length == 0){
                  // var nameObj = nameStr.split('_');
                  // for(var i = 0; i < nameObj.length; ++i){
                  //   nameObj[i] = nameObj[i].substr(0, 1).toUpperCase() + nameObj[i].slice(1);
                  // }
                  // var nameStrParsed = nameObj.join(' ');//olde code, working on name, not Hebrew comaptible
                  var nameStrParsed = attrs.placeholder + '';
                }
                else{//data-display-name attribute, the error display is different than the placeholder value
                  var nameStrParsed = attrs.displayName;
                }

                scope.fieldErrorDisplay = Boolean(nameStrParsed) ? nameStrParsed : $filter('translate')('THISFIELD');
                var valueRequired = scope.$eval(attrs.valueRequired);
                if(valueRequired && viewValueStr.length == 0 && !attrs.minLength){
                    scope.valid = false;  
                    scope.requirementSpec[nameStr] = [{
                      'msg' : scope.fieldErrorDisplay + ' ' + $filter('translate')('ISREQUIRED'),
                      'class' : undefined
                    }];
                  }
                  else{
                        // scope.fieldErrorDisplayObj[nameStr] = scope.fieldErrorDisplay + ' must meet the following requirements: ';
                        scope.requirementSpec[nameStr] = [];
                        if(attrs.minLength){
                          var itemValidity = viewValue.length >= attrs.minLength;
                          scope.valid = !itemValidity ? false : scope.valid;
                          var item = {
                            'msg' : $filter('translate')('MINLENGTH', {PARAM: attrs.minLength + ''}),
                            'class' : itemValidity ? 'valid' : undefined
                          };
                          scope.requirementSpec[nameStr].push(item);
                        }
                        else if(attrs.valueRequired){
                          var itemValidity = viewValue &&  viewValueStr && viewValueStr.length >= 1;
                          scope.valid = !itemValidity ? false : scope.valid;
                          var item = {
                            'msg' : $filter('translate')('FIELDREQUIRED'),
                            'class' : itemValidity ? 'valid' : undefined
                          };
                          scope.requirementSpec[nameStr].push(item);
                        }
                        if(attrs.maxLength){
                          var itemValidity = viewValue.length <= attrs.maxLength;
                          scope.valid = !itemValidity ? false : scope.valid;
                          var item = {
                            'msg' :  $filter('translate')('MAXLENGTH', {PARAM: attrs.maxLength + ''}),
                            'class' : itemValidity ? 'valid' : undefined
                          };
                          scope.requirementSpec[nameStr].push(item);
                        }
                        if(attrs.minLetters){
                          var itemValidity = (viewValue && /[A-z]/.test(viewValue));
                          scope.valid = !itemValidity ? false : scope.valid;
                          var item = {
                            'msg' :  $filter('translate')('MINLETTERS', {PARAM: attrs.minLetters + ''}),
                            'class' : itemValidity ? 'valid' : undefined
                          };
                          scope.requirementSpec[nameStr].push(item);
                        }
                        if(attrs.minNumbers){
                          var itemValidity = (viewValue && /\d/.test(viewValue));
                          scope.valid = !itemValidity ? false : scope.valid;
                          var item = {
                            'msg' : $filter('translate')('MINNUMBERS', {PARAM: attrs.minNumbers + ''}),
                            'class' : itemValidity ? 'valid' : undefined
                          };
                          scope.requirementSpec[nameStr].push(item);
                        }
                        if(attrs.validUrl){
                          // if(viewValue.indexOf('http') == -1){
                          //   viewValue = 'http://' + viewValue;
                          //   ctrl.$setViewValue(viewValue);
                          // }
                          // else if(viewValue.indexOf('http') != 0){
                          //   var httpIndex = viewValue.indexOf('http');w
                          //   viewValue = viewValue.substr(httpIndex);
                          //   ctrl.$setViewValue(viewValue);
                          // }
                          // var urlPattern = new RegExp("(http|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?");
                           var urlPattern = new RegExp(/^(https?):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\u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);
                           //(http|https):\/\/([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,6}?(.+){0, 100}$/i)
                          var itemValidity = !viewValue || viewValue.length == 0 || urlPattern.test(viewValue);
                          scope.valid = !itemValidity ? false : scope.valid;
                          // console.log(itemValidity);
                          var item = {
                            'msg' : $filter('translate')('VALIDURL'),
                            'class' : itemValidity ? 'valid' : undefined
                          };
                          scope.requirementSpec[nameStr].push(item);

                        }
                  }

                  if(scope.valid) {
                      ctrl.$setValidity(nameStr, true);
                      elm.removeClass('ng-required-invalid').removeClass('validatorError').removeClass('ng-invalid').addClass('ng-valid');
                      return viewValue;
                  } 
                  else {
                      ctrl.$setValidity(nameStr, false);                    
                      return undefined;
                  }
              }
              if(!scope.requirementSpec){
                scope.requirementSpec = {};
              }
              if(Boolean(attrs.valueRequired) || Boolean(attrs.minLength)){
                  ctrl.$setValidity(attrs.name, false);
                  // elm.removeClass('ng-valid').addClass('ng-invalid');
              }

            ctrl.$parsers.unshift(function(viewValue) {
              return validator(viewValue);
            });
            ctrl.$formatters.unshift(function(viewValue) {
              if(viewValue && viewValue != "" && viewValue.length > 0)
                return validator(viewValue);
            });
        }
    };
})

2 个答案:

答案 0 :(得分:2)

在我的自定义验证指令的底部添加了以下代码:

    scope.$on('triggerValidator', function(e, val){
      var viewValue = typeof $ === 'function' ? $('[name="' + attrs.name + '"]').val() : document.getElementsByName(attrs.name)[0].value;
      if(viewValue && viewValue.length > 0){
        try{
          ctrl.$setViewValue(viewValue);
          validator(viewValue);  
        }
        catch(SUPPRESS){}
      }
    });

以下是我控制器的底部:

   $timeout(function(){
        $rootScope.$broadcast('triggerValidator');
    }, 500)

请注意,使用jQuery时,200ms的超时就足够了,当使用本机JS选择器时,我不得不将超时时间增加到500ms。

在尝试设置包含char'@'的视图值时,try-catch块可以捕获Angular抛出的奇怪的解析器异常,但工作正常!。

跟踪Angular存储库中的官方问题也很好: https://github.com/angular/angular.js/issues/1460

答案 1 :(得分:1)

  

我怀疑发生这种情况是因为镀铬会在角度甚至引导之前填充字段

如果在Angular bootstraps之前设置了字段 - 它应该可以正常工作。我认为这个问题是另一回事:Chorme在Angular引导后设置字段,但它没有告知Angular状态变化。

有几种方法可行,但没有一种方法会被认为非常优雅:

  1. 手动引导 - 只需延迟150-350毫秒。
  2. 要将值保留在本地存储中并手动设置。 Here是支持它的好模块。
  3. 要以100-200ms的间隔使用$ timeout约2-10次来明确强制$digest
  4. 我可能选择3.选项,因为它最容易实现,可能最可靠。