Angularjs ui-mask与ng-pattern的配合使用

5
以下代码无法正常工作。
<input type="text"
       class="form-control input-sm"
       placeholder="hh:mm:ss"
       name="hhmmss"
       ng-model="data.hhmmss"
       ui-mask="99:99:99"
       ng-pattern="/^([0-2]|0[0-9]|1[0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]$/"
/>

当输入值为20:00:00时,formName.hhmmss.$error.patterntrue

如果删除ui-mask

<input type="text"
       class="form-control input-sm"
       placeholder="hh:mm:ss"
       name="hhmmss"
       ng-model="data.hhmmss"
       ng-pattern="/^([0-2]|0[0-9]|1[0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]$/"
    />

当输入值为20:00:00时,formName.hhmmss.$error.pattern的值为false
我该如何在ng-pattern中使用正则表达式?

1
从ng-pattern中删除^,这对我很有效。 - AndresL
从ng-pattern中删除^对我来说并不能解决这个问题。 - a2f0
2个回答

1
我遇到了同样的问题,修改了mask.js文件以在按键时更新作用域值。有一行代码可以做到这一点,但并不总是运行。
controller.$setViewValue(valUnmasked);

将if语句更新为以下内容:
if (valAltered || iAttrs.ngPattern) {

那将在按键时运行“scope.apply”并更新模型。

0

Angular 1.3.19改变了ng-pattern的行为,导致ui-mask出现问题。

目前,ng-pattern指令验证$viewValue而不是$modelValue - 参考changelog

Angular团队提供了自定义指令,可以恢复以前的行为。这是解决此问题的好方法。

当您同时使用ui-maskng-pattern时,必须向字段添加pattern-model属性。

<input type="text"
       class="form-control input-sm"
       placeholder="hh:mm:ss"
       name="hhmmss"
       ng-model="data.hhmmss"
       ng-pattern="/^([0-2]|0[0-9]|1[0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]$/"
       ui-mask="99:99:99"
       pattern-model
/>

指令的代码(将其添加到您的代码库中):

.directive('patternModel', function patternModelOverwriteDirective() {
  return {
    restrict: 'A',
    require: '?ngModel',
    priority: 1,
    compile: function() {
      var regexp, patternExp;

      return {
        pre: function(scope, elm, attr, ctrl) {
          if (!ctrl) return;

          attr.$observe('pattern', function(regex) {
            /**
             * The built-in directive will call our overwritten validator
             * (see below). We just need to update the regex.
             * The preLink fn guarantees our observer is called first.
             */
            if (angular.isString(regex) && regex.length > 0) {
              regex = new RegExp('^' + regex + '$');
            }

            if (regex && !regex.test) {
              //The built-in validator will throw at this point
              return;
            }

            regexp = regex || undefined;
          });

        },
        post: function(scope, elm, attr, ctrl) {
          if (!ctrl) return;

          regexp, patternExp = attr.ngPattern || attr.pattern;

          //The postLink fn guarantees we overwrite the built-in pattern validator
          ctrl.$validators.pattern = function(value) {
            return ctrl.$isEmpty(value) ||
              angular.isUndefined(regexp) ||
              regexp.test(value);
          };
        }
      };
    }
  };
});

ui-mask 的问题,请参考 GitHub - Reference


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接