限制HTML&中的特殊字符AngularJs [英] Restrict Special Characters in HTML & AngularJs

查看:104
本文介绍了限制HTML&中的特殊字符AngularJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 ` ~ ! @ # $ % ^ & * ( ) _ + = { } | [ ] \ : ' ; " < > ? , . /

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

I want to restrict the above mentioned special characters and numbers in the input text field. I used the

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

限制特殊字符.此模式阻止了所有特殊字符.当我想输入名称PérezGil"时,我遇到了问题,我不想限制其他语言的文字.

to restrict the special characters. This pattern is blocking all the special characters. I am facing issue when I want to enter name "Pérez Gil" I don't want to restrict other language text.

推荐答案

更新:

我认为$ parsers是这里的最佳选择.请参阅更新的代码和插件.

I think $parsers is the best options here. See the updated code and 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的更新示例

Here's a updated example on Plunker

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

旧答案:

由于您已经具有要限制的字符列表,因此可以在ng-pattern表达式中将其拼写出来,例如:

Since you already have a list of characters that you want to restrict, you can spell them out in the ng-pattern expression like:

控制器

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的一个有效示例

Here's a working example on Plunker

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

这篇关于限制HTML&amp;中的特殊字符AngularJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆