How to Restrict Special Characters in AngularJS?

Hello All ,

    In real-world applications, there are some scenarios where we don’t want to allow the user to input some characters let’s say some special characters. We can do it in 2 ways,

     The first method is the traditional way, here we write a javascript function where we check the user input for validation. If the input is unexpected then we throw an error.

    Let’s see another way that we have with angular JS.

AngularJS Directive:

    AngularJS directives are extended HTML attributes with the prefix ng-. we can use them to initialize the data (ng-init) or store the data (ng-Model) or we can create a custom directive as per the user requirement.

    Let’s create a custom directive which will not all the user to input any special character from the keyboard.

    We will be directively diving into creating directive.

Step 1:

Create a custom directive with a valid name & create a function to associate with the link function.
The link function deals with linking scope to the DOM.


 angular.module(‘ngValidInput’, [])
     .controller('ValidInputController', function($scope) {})
     .directive('validInput', function() {
        return {
             restrict: 'A',
             require: '?ngModel',
             link: checkInput
         };   
         function checkInput(scope, elem, attrs, ngModel) {
         }
     });
   

Step 2:

Create a regExpression variable where we will store all the special characters which user should not enter.

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

Step 3:

Implement the logic inside ngModel.$parsers.push function to check if the character is special then delete it automatically else keep it.

ngModel.$parsers.push(function(viewValue) {
          var regExpression = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
          
          if (viewValue.match(regExpression )) {
              return viewValue;
          }
          var oldValue = ngModel.$modelValue;
          ngModel.$setViewValue(oldValue);
          ngModel.$render();
          return oldValue;
 }); 

Hope this works fine for you all !!!

Check below for Complete Code,

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js">       </script>

</head>
<body ng-app="ngValidInput">
  <script>
  angular.module('ngValidInput', [])
    .controller('validInputController', function() {})
    .directive('validInput', function() {
      return {
            restrict: 'A',
            require: '?ngModel',
            link: checkInput
        }; 
        function checkInput(scope, elem, attrs, ngModel) {
            ngModel.$parsers.push(function(viewValue) {
              var regExpression = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./]*$/;

              if (viewValue.match(regExpression)) {
                return viewValue;
              }
              
              var oldValue = ngModel.$modelValue;
              ngModel.$setViewValue(oldValue);
              ngModel.$render();
              return oldValue;
            });
        }
       
    });
</script>
<div ng-controller="validInputController">
    <label for="input">Enter the Input Data</label>
    <input type="text" ng-model="model" id="input" name="input"  valid-input /><br>
</div>
</body>
</html>

Leave a Reply