[英]how can I make an input field only accept numbers when the input type is text?
這是我的 ID 為 label 的輸入字段,我希望此輸入字段只接受數字而不將類型更改為數字。
<label for="id">ID:</label>
<input type="text"
class="form-control form-control-sm"
formControlName="idCardInput"
name="idCard"
id="idCard"
ng-pattern="/^[0-9]*$/" />
使用 Javascript,您可以隨時在特定項目或網站中使用此 function。
function isNumberKey(event){ var charCode = (event.which)? event.which: event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; }
<input name="id" type="text" onkeypress="return isNumberKey(event)"/>
如果驗證還不夠,並且您只想接受輸入字段中的數字字符:
您可以使用 function 來測試更改時的輸入值,然后替換它,無論哪種方式,您都應該使用正則表達式:
/^\d+$/
/^[0-9]*$/
兩個選項都可以
由於您使用的是 angular,因此您可以使用 (change) 事件並調用 function 來調整綁定到輸入的表單控件的值。
您也可以使用 oninput 事件和 this.value 對輸入本身執行此操作
您需要創建 numbersOnly 指令,然后在您的 html 中使用它。使用以下 stackblitz 鏈接作為參考:
https://stackblitz.com/edit/angular-numbers-only-directive?file=app%2Fapp.component.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.