2014-01-27 63 views
2

我有一個文本框,需要驗證鍵盤和模糊事件。如果我輸入「X」,這兩個事件都會觸發,顯然您會根據下面的代碼看到兩個警報。 keyup事件是需要的,因爲我可能會根據有效值觸發某些操作,並且在按Tab鍵時還需要保留模糊事件。目標是在此顯示一個警報。 \ M/\ M/jQuery文本框驗證使用鍵控和模糊

$("#txtLength").on('keyup blur', function (e) { 
    if ($(this).val().length > 0) { 
     switch (true) { 

      case !$.isNumeric($(this).val()): 
       alert("Please enter a numeric value."); 
       $(this).focus(); 
       break 

      case ($(this).val() < 5) || ($(this).val() > 10): 
       alert("Length must be a numeric value between 5 and 10."); 
       $(this).focus(); 
       break; 

      default: 
     } 
    } 
}); 
+2

如果你在'keyup'上做了這個,除非'blur'完全不同,否則你不需要對'blur'進行驗證。 – Krishna

+2

你確實需要它。如果您僅使用關鍵事件,您將獲得警報,並將設置焦點。但是,用戶現在可以在文本框的Tab鍵之外留下無效值。 – 80sRocker

+0

你的陳述在這裏是錯誤的。 _如果我輸入「X」,這兩個事件都會fire_http://jsfiddle.net/EbLdf/ ..只有keyup事件被激發。 – Krishna

回答

4

感謝您的所有輸入。一些好的想法有助於解決問題。堅持話題,避免使用.on按鍵和模糊顯示兩個警報,這是我最終做的。

var bAlertCalled = false; 

$("#txtLength").on('keyup blur', function (e) { 
    if (bAlertCalled === true) { 
     bAlertCalled = false; 
     return; 
    } 

    if ($(this).val().length > 0) { 
     var iLength = parseInt($(this).val()); 

     switch (true) { 
      case !$.isNumeric($(this).val()): 
       bAlertCalled = true; 
       $(this).focus(); 
       alert("Please enter a numeric value."); 
       break 

      case (iLength < 5) || (iLength > 10): 
       bAlertCalled = true; 
       $(this).focus(); 
       alert("Length must be a numeric value between 5 and 10."); 
       break; 

      default: 
     } 
    } 
}); 
0

這樣看來,如果你使用警報()或中斷用戶的一些其它方法只會造成一個問題。使用內聯驗證的形式,用戶可能永遠不會注意到。另外,你的價值的檢查沒有工作,因爲 「6」 是不是> 5或者< 10.我固定,使用parseInt函數:

HTML:

<input type="text" id="txtLength" /> <span id='spanLengthValidation'></span> 

腳本

$("#txtLength").on('keyup blur', function (e) { 
    $("#spanLengthValidation").text(""); 
    var amt = parseInt($(this).val()) 
    if ($(this).val().length > 0) { 
     switch (true) { 
     case !$.isNumeric($(this).val()): 
      $("#spanLengthValidation").text("Please enter a numeric value."); 
      $(this).focus(); 
      break; 

     case (amt < 5) || (amt > 10): 
      $("#spanLengthValidation").text("Length must be a numeric value between 5 and 10."); 
      $(this).focus(); 
      break; 

     default: 
     } 
    } 
}); 
+0

謝謝。這是使用警報的好選擇... – 80sRocker