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.

2
  • Use a negative set: [^ ] or if you want to disallow every whitespace character: [^\s] Commented Nov 17, 2018 at 19:45
  • Did any of these answers fix the issue for you? Commented Nov 18, 2018 at 17:16

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Great solution! You can also use the simple (keydown) and then call a function that checks which keyboard key was pressed, and handle it according to your needs :)
Simplest solution which actually works! Thanks.
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

1 Comment

It works with e.key === ' ' (one empty space). thanks!
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]+)*$"

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.