Strip Invalid Characters From Form Fields

In this example below you will see how to do a Strip Invalid Characters From Form Fields with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 007design, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 007design ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Strip Invalid Characters From Form Fields</title>
  
  
  
  
  
</head>

<body>

  <div data-ng-app="app">
  Address<br>
  <input type="text" name="address" data-ng-model="something" />
  <br><br>
  Street<br>
  <input type="text" name="street" />
  <br><br>
  Unit<br>
  <input type="text" name="unit" />
  <br><br>
  Suite<br>
  <input type="text" name="suite" />
  <br><br>
  Apt<br>
  <input type="text" name="apt" />
  <br><br>
  Zipcode<br>
  <input type="text" name="zipcode" />
  <br><br>
  Zip<br>
  <input type="text" name="zip" />
  <br><br>
  Postal<br>
  <input type="text" name="postal" />
</div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/007design/strip-invalid-characters-from-form-fields-WRbepO */
angular.module('app', [])
.directive('input', [function() {
  return {
    restrict: 'E',
    require: '?ngModel',
    link: function(scope, elem, attrs, ngModel) {
      var patterns = {
        address: /[^A-Za-z0-9\-\., ]/,
        unit: /[^A-Za-z0-9\- ]/,
        postal: /[^A-Za-z0-9]/,
        zip: /[^A-Za-z0-9\-]/
      };
      if (attrs.type !== 'text') return;
      
      var pattern;
      if (attrs.name.match(/address|street/i))
        pattern = patterns.address;
      else if (attrs.name.match(/unit|suite|apt/i))
        pattern = patterns.unit;
      else if (attrs.name.match(/zip|postal/i))
        pattern = patterns.zip;
      else if (attrs.name.match(/postal/i))
        pattern = patterns.postal;
      else return;
      
      if (ngModel)
        ngModel.$parsers.unshift(function(input) {
          var x = input.replace(pattern, '') || '';
          if (x !== input) {
            ngModel.$setViewValue(x);
            ngModel.$render();
          }
          return x;
        });
      else
        elem.on('keyup', function(e) {
          if (/37|39|91/.test(e.keyCode)) return;
          var elm = angular.element(this)
          elm.val(elm.val().replace(pattern, ''));
        });
    }
  };
}])

Comments