代码之家  ›  专栏  ›  技术社区  ›  kaka1234

限制正斜杠的指令[关闭]

  •  0
  • kaka1234  · 技术社区  · 6 年前

    一切工作良好,但它也允许向前斜杠。我错过了什么?

    下面是我的指令和命令: 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;
    
        });
      }
    }
    });
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   lenilsondc    6 年前

    如果您想替换除 \w , _ [^\w_ ] (当然逃走了)。

    用下面的代码替换代码中的regex:

    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>
        2
  •  0
  •   Theo    6 年前

    我想你错过了逃出前斜线的机会

    regReplace = new RegExp('[^\\w_\/\s\/g]', 'ig');