$ validValidity在validRegex指令中

时间:2014-05-29 14:25:53

标签: javascript regex angularjs angularjs-directive

我有这样的指示:

  .directive('validRegex', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function (scope, element, attrs, ngModel) {
        ngModel.$parsers.unshift(function(viewValue) {
          console.log(viewValue);
          try {
            var regex = new RegExp(viewValue);
            ngModel.$setValidity('notRegex', true);
            return viewValue;
          } catch(e) {
            ngModel.$setValidity('notRegex', false);
            return undefined;
          }
        });
      }
    };
  })

我用它像:

  <div class="col-sm-7">
    <input class="form-control" valid-regex id="search-text" type="text" ng-model="selectedSearchText"/>
    <span ng-show="selectedSearchText.$error.notRegex" class="form-error">
      Invalid Regular Expression
      <span class="icon-attention app_icon"></span>
    </span>
  </div>
  <p>{{selectedSearchText}}</p>

如果正则表达式无效,则文本不会按预期显示,但不会显示错误消息。我搜索了SO但没有找到解决办法。

1 个答案:

答案 0 :(得分:1)

您必须使用以下格式将输入字段括起来

<form name="form">

    <div class="col-sm-7">
    <input class="form-control" valid-regex id="search-text" type="text" ng-model="selectedSearchText" name="selectedSearchText"/>
    <span ng-show="form.selectedSearchText.$error" class="form-error">
      Invalid Regular Expression
      <span class="icon-attention app_icon"></span>
    </span>
  </div>
  <p>{{selectedSearchText}}</p>
  </form>