Warrior Warrior - 1 month ago 21
HTML Question

Restrict Special Characters in 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 ]*$/"


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 . Anyone please help.

Answer

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

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

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

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

Here's a working example on Plunker

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