![](/img/trans.png)
[英]How to restrict input field from accepting special characters in Angular?
[英]How to restrict reserved characters in input field using angular8
嗨,我在我的應用程序中使用 angular8,我有一個文件名輸入字段,它應該包含字母數字字符,除了保留字符之外,其他特殊字符是允許的。 有什么方法可以為該代碼或內聯代碼提供指令,並且它必須限制粘貼這些保留字符。
不應允許使用以下保留字符:
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
HTML:
<input type="text" class="form-control" placeholder="Custom File Name" name="fileName" autocomplete="off" (keypress)="keyPress($event)">
TS:
public keyPress(event: any) {
const pattern = /[0-9\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar) && event.charCode != '0') {
event.preventDefault();
}
}
使用反應形式並清理更改的輸入。 適用於復制粘貼和打字。
public restricted = new FormControl();
ngOnInit() {
this.restricted.valueChanges.subscribe((val) => {
const restrictedCharacters = /[-+]/g // Add more restricted characters here
if (restrictedCharacters.test(val)) {
this.restricted.setValue(val.replace(restrictedCharacters, ''))
}
});
}
在您的模板中,將受限表單控件添加到您的輸入中。
<input
[formControl]="restricted"
type="text"
placeholder="Custom File Name"
name="fileName"
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.