簡體   English   中英

限制輸入字段中的字符

[英]Restrict characters in input field

有沒有辦法阻止用戶在輸入字段中輸入特定字符? 我嘗試了下面的代碼,但是當用戶輸入不允許的字符時,它們會出現一小段時間然后消失。 我希望在寫入無效字符時輸入保持不變。

我想用onchange是因為其他的限制方法在移動設備上好像不起作用。 我要解決的問題是字符在被刪除之前會短暫出現。

 function checkInput(ob) { const invalidChars = /[^0-9]/gi; if(invalidChars.test(ob.value)) { ob.value = ob.value.replace(invalidChars, ""); } };
 <input class="input" maxlength="1" onChange="checkInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />

你可以試試這個,

$('.input').keyup(function () {
    if (!this.value.match(/[0-9]/)) {
        this.value = this.value.replace(/[^0-9]/g, '');
    }
});

看這個小提琴演示

更新 :

你可以試試這個代碼,

$(document).ready(function() {
    $(".input").keydown(function (e) {
        // Allow: backspace, delete, tab, escape and enter
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

來源

查看更新的小提琴演示

為安卓更新:

<EditText
android:id="@+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="58dp"
android:layout_toRightOf="@+id/textView1"
android:maxLength="1" >
</EditText>

我認為它可以幫助你......使用android:inputType="number"你可以做到這一點。

按鍵和粘貼事件的組合有一個技巧:

 var text = document.getElementById('text'); text.onkeypress = text.onpaste = checkInput; function checkInput(e) { var e = e || event; var char = e.type == 'keypress' ? String.fromCharCode(e.keyCode || e.which) : (e.clipboardData || window.clipboardData).getData('Text'); if (/[^\\d]/gi.test(char)) { return false; } }
 <input class="input" maxlength="10" id="text" type="text" autocomplete="off" />

此代碼可防止鍵入或粘貼除數字以外的任何內容。 也沒有閃爍和無效字符不顯示。

適用於 IE7+。

演示: http : //jsfiddle.net/VgtTc/3/

這是您可以嘗試的小技巧: DEMO

它的作用是將每個輸入文本着色為白色,然后在滿足您的要求時將其改回黑色。 如果您能忍受輸入有效字符時出現的延遲。

function checkInput(ob) {
    var invalidChars = /[^0-9]/gi
    if (invalidChars.test(ob.value)) {
        ob.value = ob.value.replace(invalidChars, "");
    }
    else {
        document.getElementById('yourinput').style.color = '#000';
    }
};

function hideInput(ob) {
    document.getElementById('yourinput').style.color = '#FFF';
};

html

<input id="yourinput" class="input" maxlength="1" onKeydown="hideInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />

css

input {color:#FFF;}
<input id="testInput"></input>

<script>
testInput.onchange = testInput.oninput = restrict;

function restrict() {
    testInput.value = testInput.value.replace(/[^a-z]/g, "");
}
</script>

我想出了一些稍微不同的東西。 oninput 代替 onkeyup/onkeydown,以及 onchange 代替 onpaste。

檢查此代碼,

$('.input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();
});

到目前為止給出的所有答案都至少存在以下可訪問性問題之一:

  1. 他們驗證鍵碼,這不適用於非 QWERTY 鍵盤布局。
  2. 它們並未涵蓋所有輸入法; 特別是拖放經常被遺忘。
  3. 他們改變了value ,重置了插入符號的 position。
  4. 他們使用pattern屬性,但這在提交表單之前不會提供反饋。

在插入之前實際驗證輸入不是更好的主意嗎?


beforeinput事件在輸入值改變之前觸發。 該事件有一個data屬性,它描述了用戶想要添加到輸入字段的內容。 在事件處理程序中,您只需檢查data屬性,如果包含不允許的字符則停止事件鏈。

我們最終得到以下非常簡單、非常短的代碼。

 const input = document.getElementById("input"); const regex = new RegExp("^[0-9]*$"); input.addEventListener("beforeinput", (event) => { if (event.data.= null &&.regex.test(event;data)) event;preventDefault(); });
 <label for="input">Enter some digits:</label> <input id="input" />


一些結束語:

  • 輔助功能:清楚地解釋用戶期望的輸入格式。 例如,您可以使用輸入的title屬性來顯示解釋預期格式的工具提示。
  • 安全性:這是客戶端驗證,不保證在將表單發送到服務器時強制執行該模式。 為此,您需要服務器端驗證。

我在按鍵和粘貼事件上都限制了無效字符,例如:

<input type="text" onkeydown="validateKey(event)" onpaste="validatePaste(this, event)">  

並在選項卡或單獨的 javascript 文件中定義處理這些事件的函數:

<script>
function validateKey(e) {
  switch(e.keyCode) {
    case 8,9,13,37,39:
      break;
    default:
      var regex = /[a-z .'-]/gi;
      var key = e.key;
      if(!regex.test(key)) {
        e.preventDefault();
        return false;
      }
      break;
  }
}
function validatePaste(el, e) {
  var regex = /^[a-z .'-]+$/gi;
  var key = e.clipboardData.getData('text')
  if (!regex.test(key)) {
    e.preventDefault();
    return false;
  }
}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM