[英]Spaces issue in inputbox in Angular/Regex? I need to restrict the first space and then allow user to enter space after first character
[英]How to restrict white space as first character and allow space after character in angular8
我試圖將特殊字符和空格限制為第一個字符,但我能夠實現限制特殊字符,但我無法將空格限制為第一個字符。 我使用過自定義管道。 還附上了工作演示。 所以現在,輸入字段中的特殊字符已被限制,因此我必須將空格限制為第一個字符,並在字母數字之后允許空格。
HTML:
<input type="text" class="form-control min-w300" placeholder="Search Agent" [(ngModel)]="wildCardSearch" (ngModelChange)="searchChange($event)" appInputRestriction>
Ts:我把選擇器當作appInputRestrictor
並且我是這樣使用它的。
regexStr = '^[a-zA-Z0-9_]*$';
@Input() isAlphaNumeric: boolean;
constructor(private el: ElementRef) { }
@HostListener('keypress', ['$event']) onKeyPress(event) {
return new RegExp(this.regexStr).test(event.key);
}
validateFields(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100)
}
您正在尋找的解決方案稱為this.el.nativeElement.selectionStart
這是您的代碼庫。
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if ( this.el.nativeElement.selectionStart === 0 && event.key === ' ' ) {
event.preventDefault();
}
if (!RegExp(this.regexStr).test(event.key)) {
event.preventDefault();
}
}
我也為此創建了演示。 請檢查這個:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.