限制 HTML 和 AngularJs 中的特殊字符

新手上路,请多包涵
 ` ~ ! @ # $ % ^ & * ( ) _ + = { } | [ ] \ : ' ; " < > ? , . /

我想在输入文本字段中限制上述特殊字符和数字。我用了

ng-pattern="/^[a-zA-Z ]*$/"

限制特殊字符。此模式阻止了所有特殊字符。当我想输入名称“Pérez Gil”时遇到问题我不想限制其他语言文本。

原文由 Warrior 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 315
2 个回答

更新:

我认为 $parsers 是最好的选择。查看更新的代码和 plunker。

控制器

angular.module('ngPatternExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.regex = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
  }])
  .directive('myDirective', function() {
     function link(scope, elem, attrs, ngModel) {
          ngModel.$parsers.push(function(viewValue) {
            var reg = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
            // if view values matches regexp, update model value
            if (viewValue.match(reg)) {
              return viewValue;
            }
            // keep the model value as it is
            var transformedValue = ngModel.$modelValue;
            ngModel.$setViewValue(transformedValue);
            ngModel.$render();
            return transformedValue;
          });
      }

      return {
          restrict: 'A',
          require: 'ngModel',
          link: link
      };
  });

模板

<input type="text" ng-model="model" id="input" name="input" my-directive />

这是 Plunker 上的更新示例

https://plnkr.co/edit/eEOJLi?p=preview

旧答案

由于您已经有了要限制的字符列表,因此您可以在 ng-pattern 表达式中拼出它们,例如:

控制器

angular.module('ngPatternExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
      $scope.regex = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
  }]);

模板

<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" />

这是 Plunker 上的一个工作示例

https://plnkr.co/edit/eEOJLi?p=preview

原文由 Peng 发布,翻译遵循 CC BY-SA 3.0 许可协议

Use Directives to restrict Special characters:

 angular.module('scPatternExample', [])
      .controller('scController', ['$scope', function($scope) {
      }])
    .directive('restrictSpecialCharactersDirective', function() {
         function link(scope, elem, attrs, ngModel) {
              ngModel.$parsers.push(function(viewValue) {
                var reg = /^[a-zA-Z0-9]*$/;
                if (viewValue.match(reg)) {
                  return viewValue;
                }
                var transformedValue = ngModel.$modelValue;
                ngModel.$setViewValue(transformedValue);
                ngModel.$render();
                return transformedValue;
              });
          }

          return {
              restrict: 'A',
              require: 'ngModel',
              link: link
          };
      });

In Html:
    <input type="text" ng-model="coupon.code" restrict-Special-Characters-Directive>

原文由 Pulkit-aggarwal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题