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.
-
What have you tried so far? I would suggest you write a custom directive which watches keyCode on keydown and take appropriate actions. – Aniket Sinha Dec 05 '14 at 19:30
9 Answers
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>

- 1
- 1

- 43,526
- 67
- 220
- 351
-
4
-
1What would happen if user pasted a string with spaces to an input? – Ilya Luzyanin Nov 08 '16 at 20:23
-
1@IlyaLuzyanin Good question. My original directive probably wouldn't have worked in that case. I replaced my answer with a directive that does account for spaces being pasted in. – Jason Swett Nov 08 '16 at 21:05
-
3Nice one, I didn't know about `input` event up until now :). The problem with this solution though is that it places cursor to the end of the string if you are trying to change the text in the middle or in the beginning. What I ended up doing is taking your initial solution + solution from another similar question: https://plnkr.co/edit/BqPFIMDfO2HtlERL9QWk?p=preview. Seems to work – Ilya Luzyanin Nov 08 '16 at 21:31
-
I have applied this but I type random data and press back space for long time then must letters comes in the input field. – Anjana Aug 21 '17 at 14:05
<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, '');
}
});
}
};
});

- 301
- 3
- 12
-
Why use a `split()` followed by a `join()` if you can use a simple `replace()` instead? – PLPeeters Oct 31 '17 at 15:39
If you want to achieve it without writing directive
ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()"

- 91
- 1
- 2
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();
}
});
}
}
});

- 725
- 2
- 8
- 22
-
-
I see. Well this works to prevent special chars, maybe it's adaptable to disallow spaces too. Pasting wont work here: http://kopy.io/KNoU1 – Bento Mar 10 '17 at 13:25
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;
});
}
}
});

- 725
- 2
- 8
- 22
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 />

- 41
- 8
You can achieve this without writing a directive.
<input ng-model="myModel" ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()">

- 575
- 1
- 7
- 12
For Angular 9 ,Keycode is not support.
Below code can help you for that.
keyDownHandler(event) {
if (event.code === 'Space') {
event.preventDefault();
}
}

- 1,671
- 17
- 18
You can define a directive for this. Tested with Angular v16
import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
selector: '[appInputTrim]'
})
/**
* This directive is used to trim the input value.
* @author Hakkı Konu
*/
export class InputTrimDirective {
constructor(private el: ElementRef) {
}
@HostListener('input', ['$event.target.value'])
trim(value: string) {
this.el.nativeElement.value = value.trim();
console.log('value', value);
}
}
usage
<input appInputTrim .... />

- 6,181
- 6
- 62
- 106