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.
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.
/^[^\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.
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.
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]+)*$"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With