首页 > 解决方案 > 限制正斜杠的指令

问题描述

我创建了一个不允许 spl 字符(下划线和空格除外)的指令。一切正常,但它也允许正斜杠。我在这里想念什么?

以下是我的指令和 plunkr:http ://plnkr.co/edit/ho6kztdlYau4Zi29Afa5?p=preview

.directive('noSpecialChar', function() {
return {
  require: 'ngModel',
  restrict: 'A',
  link: function(scope, element, attrs, modelCtrl) {
    modelCtrl.$parsers.push(function(inputValue) {
      if (inputValue === undefined)
        return ''

    regReplace = new RegExp('[^\\w_/\s/g]', 'ig');
      if (inputValue === undefined)
          return ''
      cleanInputValue = inputValue.replace(regReplace, '');
      if (cleanInputValue != inputValue) {
          modelCtrl.$setViewValue(cleanInputValue);
          modelCtrl.$render();
      }
      return cleanInputValue;

    });
  }
}
});

标签: javascriptangularjsregex

解决方案


您的正则表达式没有正确构建,如果您想替换除\w,_和之外的所有内容,您应该使用这个:([^\w_ ]当然转义)。

用下面的代码替换代码中的正则表达式:

new RegExp('[^\\w_ ]', 'gi')

注意\s\s不仅匹配常规空格字符( ),而且还匹配其他类型的空格(\r\n\t\f\v)。所以,我相信你不应该使用它,因为你似乎不希望在你的输入中允许其他类型的空白。

检查下面的工作代码。

angular.module('app', [])
  .controller('myCtrl', function($scope) {
    $scope.username = '';
  })
  .directive('noSpecialChar', function() {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function(scope, element, attrs, modelCtrl) {
        modelCtrl.$parsers.push(function(inputValue) {
          if (inputValue === undefined)
            return ''

          regReplace = new RegExp('[^\\w_ ]', 'gi');
          if (inputValue === undefined)
            return ''
          cleanInputValue = inputValue.replace(regReplace, '');
          if (cleanInputValue != inputValue) {
            modelCtrl.$setViewValue(cleanInputValue);
            modelCtrl.$render();
          }
          return cleanInputValue;

        });
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  Username : <input type="text" no-special-char ng-model="username" name="userName">
</div>


推荐阅读