Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Form Input block (space) REGEX

Tags:

regex

angular

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.

like image 372
Tom O'Brien Avatar asked Nov 17 '18 19:11

Tom O'Brien


People also ask

How do you restrict whitespace in regex?

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.

How can you prevent someone from entering space at the beginning of a textbox?

/^[^\t]. */ checks if the string starts with any character but a space, if you want to exclude all white spaces use /^[^\s]. */ instead. And now add the required and NoWhiteSpaceAtBeginn as class names to the fields you want to validate.


Video Answer


2 Answers

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.

like image 169
SiddAjmera Avatar answered Oct 24 '22 00:10

SiddAjmera


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]+)*$"

like image 37
Vict01 Avatar answered Oct 24 '22 02:10

Vict01