簡體   English   中英

使用JavaScript進行字段驗證-onkeyup?

[英]Field validation with JavaScript - onkeyup?

我在這里有一個由onkeypress觸發的代碼...我希望它在有特殊字符輸入時發出警報。 除警報外,如果用戶將在字段中鍵入特殊字符,則應刪除鍵入的特殊字符,並且焦點應返回到該字段。 我似乎無法擺脫這個問題。 你能幫助我嗎? 提前致謝

function ei(e)
{
  var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
  for (var i = 0; i < e.value.length; i++) {
    if (iChars.indexOf(e.value.charAt(i)) != -1) {
      alert ("Please do not use special characters.");
      e.value = e.value-1;
      e.focus();
      return false;
    }
  }
}

這將在文本字段中調用。

<input type="text" name="name" onkeyup="ei(this)">

這里發生了一些奇怪的事情。

  1. 您不想使用HTML元素的onkeyup屬性。 綁定事件監聽器功能,使您的代碼更具模塊化。
  2. 就像其他人所說的那樣,您不能使用減法運算符。
  3. 您可能不想每次有人鍵入無效字符時都發出警報。 那只會惹惱和激怒用戶。 我只是將其記錄到控制台,但是您應該考慮將錯誤文本放在input元素旁邊。

     $(function () { function ei(e) { var iChars = "!@#$%^&*()+=-[]\\\\\\';,./{}|\\":<>?"; for (var i = 0; i < this.value.length; i++) { if (iChars.indexOf(this.value.charAt(i)) != -1) { console.log("Please do not use special characters."); this.value = this.value.slice(0, this.value.length - 1); this.focus(); return false; } } } $('#hurp').on('keyup', ei); }); 

並向您的輸入元素添加一個id:

<input type="text" name="name" id="hurp">​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

看到這個JSFiddle: http : //jsfiddle.net/QgLcB/

e.value = e.value-1; 沒有按照你的想法做。

您可能要使用substr()

為什么要打擾使用keyup事件? 最好使用keydownkeypress事件然后將其取消(我使用此站點來查找鍵碼):

function ei (event) {
    event = event || window.event;

    switch (event.keyCode) {
        case 47: //.
        case 33: //!
        //etc
            event.preventDefault(); //cancel the current action, which will stop it writing out to the textbox
            break;
        default:
            break;
    }
}

我還建議您研究jQuery,而不要使用內聯JavaScript來掛接事件,並查看jQuery Validation插件,因為這應有助於處理大量代碼。

暫無
暫無

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

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