Harish
Harish

Reputation: 15

restrict space at first position in textbox using Angular 6

I have a situation where I need to restrict users from entering space in the beginning of a TextBox. I am able to restrict space entry in TextBox. But not having any clues about not allowing at first position.

I am looking for a solution using Angular 6. Any help would be appreciated.

Upvotes: 0

Views: 9693

Answers (3)

raji naidu
raji naidu

Reputation: 1

<input type="text" (keydown)="space($event)" name="name"/>

// TS File

public space(event:any){

if (event.target.selectionStart === 0 && event.code === 'Space'){
  event.preventDefault();
}

}

Upvotes: 0

Kiran Shinde
Kiran Shinde

Reputation: 5982

HTML

<input type="text" (click)="handleInput($event)">

TS

handleInput(event) {
    if (event.which === 32 && !this.value.length)
        event.preventDefault();
}

This will not allow user to add space at first place only

Upvotes: 0

wentjun
wentjun

Reputation: 42546

There are two ways to achieve it with Vanilla JavaScript.

1) The use of string.replace() with Regex.

Explanation: ^ matches the starting position (leading),\s matches a white-space character, and + matches the subsequent elements. When you use them together, ^\s+ will match 1 or more leading spaces.

const originalString = '      my Name is WenTjun';
const result = originalString.replace(/^\s+/g, '');
console.log(originalString);
console.log(result);

2) The use of String.trim(). Do note that this trims both leading and trailing spaces, hence you might not want to use this if you wish to preserve the trailing spaces.

const originalString = '      my Name is WenTjun';
const result = originalString.trim();
console.log(originalString);
console.log(result);

Upvotes: 1

Related Questions