angular restriction to not allow spaces in text field

All we need is an easy explanation of the problem, so here it is.

I do not want a user to enter spaces in a text field. I don’t want it on submit validation but rather – a space will not show up on the text field when they click it.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The selected answer is arguably not very unobtrusive. And if you need to use it in multiple places, you’ll end up with duplicated code.

I prefer to prevent the input of spaces using the following directive.

app.directive('disallowSpaces', function() {
  return {
    restrict: 'A',

    link: function($scope, $element) {
      $element.bind('input', function() {
        $(this).val($(this).val().replace(/ /g, ''));
      });
    }
  };
});

This directive can be invoked like this:

<input type="text" disallow-spaces>

Method 2

<input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text">

Update:
To improve code quality you can create custom directive instead. But don’t forget that your directive should prevent input not only from keyboard, but also from pasting.

<input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue">

Here is important to add ng-trim=”false” attribute to disable trimming of an input.

angular
  .module('app')
  .directive('restrictField', function () {
    return {
        restrict: 'AE',
        scope: {
            restrictField: '='
        },
        link: function (scope) {
          // this will match spaces, tabs, line feeds etc
          // you can change this regex as you want
          var regex = /\s/g;

          scope.$watch('restrictField', function (newValue, oldValue) {
              if (newValue != oldValue && regex.test(newValue)) {
                scope.restrictField = newValue.replace(regex, '');
              }
          });
        }
    };
  });

Method 3

If you want to achieve it without writing directive

ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()"

Method 4

THe directive Jason wrote did not work for me. I had to change return false to: e.preventDefault() like so:

app.directive('disallowSpaces', function() {
    return {
        restrict: 'A',

        link: function($scope, $element) {
            $element.bind('keydown', function(e) {
                if (e.which === 32) {
                    e.preventDefault();
                }
            });
        }
    }
});

Method 5

This works to prevent entering any special chars including spaces:

app.directive('noSpecialChar', function() {
return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
        modelCtrl.$parsers.push(function(inputValue) {
            if (inputValue == null)
                return ''
            let cleanInputValue = inputValue.replace(/[^\w]|_/gi, '');
            if (cleanInputValue != inputValue) {
                modelCtrl.$setViewValue(cleanInputValue);
                modelCtrl.$render();
            }
            return cleanInputValue;
        });
    }
}
});

Method 6

Use without jquery

 angular.module('app').directive('disallowSpaces', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      maxvalue: '=',
    },
    link: function ($scope, $element, attr, ngModelCtrl) {
      $element.bind('keydown', function () {
        function transformer(text) {
          if (text) {
            var transformedInput = text.replace(/ /g, '');
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
            return transformedInput;
          }
          return undefined;
        }
        ngModelCtrl.$parsers.push(transformer);
      });
    },
  };
});

// use disallow-spaces

<input type="text" ng-model="name" disallow-spaces />

Method 7

You can achieve this without writing a directive.

<input ng-model="myModel" ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()">

Method 8

For Angular 9 ,Keycode is not support.

Below code can help you for that.

keyDownHandler(event) {

    if (event.code === 'Space') {
        event.preventDefault();
    }
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply