![](/img/trans.png)
[英]HTML text input, using JS regex to only allow certain characters to be typed
[英]Using Regex to only allow certain characters in HTML input field seems not to work when starting with a not allowed character
我試圖只允許用戶使用以下正則表達式鍵入/復制到 HTML- <input>
字段中的某些字符:
return /^[A-Za-z0-9 ]*$/.test(value);
它適用於我,但前提是我以允許的字符開頭(例如:“ A ”)。
但是,如果我從我的正則表達式不允許的字符開始(例如:“ ! ”),我突然可以輸入應該禁用的字符:
為了進行測試,我創建了以下小提琴: >>Click<<
完整腳本作為參考:
<input type="text" class="polarion-TextBox" name="targetDocument" style="width: 100%;">
<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function() {
window.setTimeout ( function() {
// Restricts input for the given textbox to the given inputFilter.
function setInputFilter(textbox, inputFilter) {
["input"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
});
}
// Restrict input to digits and '.' by using a regular expression filter.
setInputFilter(document.getElementsByName("targetDocument")[0], function(value) {
return /^[A-Za-z0-9 ]*$/.test(value);
});
}, 1000);
}, false);
</script>
您可以將初始 oldValue 設置為空字符串來解決此問題。
添加textbox.oldValue = "";
在textbox.addEventListener
之前。
這對我有用:
function setInputFilter(textbox, inputFilter) { ["input"].forEach(function(event) { textbox.addEventListener(event, function() { if (inputFilter(this.value)) { if (this.hasOwnProperty("oldValue")) { this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { this.value = ""; this.setSelectionRange(0, 0); } } else { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } }); }); } window.addEventListener("DOMContentLoaded", function() { setInputFilter(document.getElementsByName("targetDocument")[0], function( value ) { return /[^A-Za-z0-9 ]/g.test(value); }); });
<input type="text" class="polarion-TextBox" name="targetDocument" style="width: 100%;">
如果在無效輸入上沒有oldValue
可恢復,則主要更改是清除該value
。 如果有任何無效字符,我還反轉了邏輯並返回true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.