Javascript $setValidity内部validRegex指令

Javascript $setValidity内部validRegex指令,javascript,regex,angularjs,angularjs-directive,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(viewValu

我有这样的指示:

  .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>

无效正则表达式
{{selectedSearchText}}


如果正则表达式无效,则文本不会按预期显示,但不会显示错误消息。我已经搜索过了,但没有找到修复方法。

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

<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>

无效正则表达式
{{selectedSearchText}}


请仔细阅读(再次)。谢谢,我刚刚在Documentation link@Blackhole give的评论中发现了这一点。