Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict Special Characters in HTML & AngularJs

Tags:

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.

like image 722
Warrior Avatar asked Oct 20 '25 13:10

Warrior


1 Answers

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

like image 130
Peng Avatar answered Oct 23 '25 02:10

Peng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!