5

I have an input field in my Angular component in which i want to not allow a user to be able to type a (space).

I've tried using

<input type="text" [(ngModel)]="inputText" pattern="[a-zA-Z]">

which wasn't what i wanted, and it didn't work anyways!

Does anybody know what the correct regex pattern to just block the (space) key is? And what is the correct way to use the pattern, as the above pattern didn't work...

Thanks in advance.

Tom O'Brien
  • 1,741
  • 9
  • 45
  • 73

4 Answers4

14

Using RegEx will still allow the user to type in space. But it will mark the field as invald if a pattern validator is applied to it.

If you don't really want to allow the user to type in space in the first place, you'll have to prevent it by listening to the keydown event on the input and then handling it to prevent its default behaviour. Here, give this a try:

<input type="text" (keydown.space)="$event.preventDefault()">

Here's also a Sample StackBlitz for your ref.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
1

The best way of addressing this problem is by writing the directive which you can use on multiple locations.

Here is the Stackblitz sample for the same

Kedar9444
  • 1,745
  • 1
  • 11
  • 15
1

If you want to allow any type of character except spaces alone without any letters, you can use this: "^\w+( +\w+)*$"

If you also want to use accented vowels, you can use this: "^[a-zA-Zá-úÁ-Ú0-9]+( +[a-zA-Zá-úÁ-Ú0-9]+)*$"

Vict01
  • 300
  • 1
  • 10
0

You can use the following pattern:

<input pattern="[^\s]*">
  • [^\s] is a negative set which matches every character which is not in the set.
  • \s matches a white space character (e.g. space, tab, etc.)
  • * matches 0 or more character of the preceding item

Here is an example of how the browser checks if the pattern is correct (i.e. Google Chrome for example does not allow you to submit the form if there is a whitespace character in it. Test it here (enter a string containing a white space and hit Submit):

<form>
  <input pattern="[^\s]*">
  <button type="submit">Submit</button>
</form>
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87