Restrict Special Characters in HTML & AngularJs

后端 未结 3 1446
你的背包
你的背包 2021-01-14 05:24
 ` ~ ! @ # $ % ^ & * ( ) _ + = { } | [ ] \\ : \' ; \" < > ? , . /

I want to restrict the above mentioned special characters and numbers i

3条回答
  •  情深已故
    2021-01-14 05:56

    Updates:

    I think $parsers is the best options here. See the updated code and plunker.

    Controller

    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
          };      
      });
    

    Template

    
    

    Here's a updated example on Plunker

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

    Old Answers:

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

    Controller

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

    Template

    
    

    Here's a working example on Plunker

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

提交回复
热议问题