在validRegex指令中设置有效性



我有这样的指令:

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

如果regex无效,则文本不按预期显示,但没有错误消息。我已经搜索了SO,但没有找到修复

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

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

最新更新