2017-08-07 41 views
0

正常工作,我想阻止用戶使用輸入 字母鍵和我jQuery的使用下面的代碼正則表達式不是按鍵

var enK = /^(6[5-9])|([7-9][0-9])|(1([01][0-9]|2[0-2]))$/y; 
// this regex is for event code of a-z and A-Z letters in keypress event 
$(document).ready(function(){ 
    $('input').bind('keypress',function(evt){ 
     var evC = evt.which || evt.charCode; 
     if(enK.test(evC)){ 
      event.preventDefault(); 
     } 
    }) 
}); 

的Test1:

輸入鍵:ABCDEFG

輸出:bdf

Test2:

輸入按鍵:AAAAAA

輸出:AAA

這些試驗是指:

- 第一按鍵防止

-Second按鍵不匹配正則表達式到並不會阻止

- 第三按鍵被阻止

- 第四個按鍵不匹配正則表達式並且不會阻止

...

以下代碼具有相同的resualt。

var enC = /[a-z|A-Z]/g; 
$(document).ready(function(){ 
    $('input').bind('keypress',function(evt){ 
     var evC = evt.which || evt.charCode; 
     evC = String.fromCharCode(evC); 
     if(enC.test(evC)){ 
      event.preventDefault(); 
     } 
    }) 
}); 

現在我該如何解決這個問題?謝謝。

+0

你的正則表達式並沒有做任何接近檢查任何字母的操作。根據你提供的內容,我不知道你在這裏要做什麼。 –

+0

@SpencerWieczorek它檢查鍵碼。 'a' = 97,等等。 – Jorg

+1

@Jorg檢查數值而不是檢查鍵碼是否容易?正則表達式對數字範圍並不是很好。 –

回答

1
$(document).ready(function(){ 
    $('input').bind('keypress',function(evt){ 
    var key = String.fromCharCode(evt.which || evt.charCode); 
    if(/[a-z]/i.test(key) === false) evt.preventDefault(); 
    }) 
}); 

這可以防止除a-z和A-Z之外的所有輸入。

https://jsfiddle.net/0b2f7wyL/1/

@fubar在評論中有正確的答案:y是「粘着」標誌,它告訴正則表達式查找匹配的lastIndex的,只在lastIndex的(不早於或晚於字符串),這就是爲什麼其他檢查失敗的原因。