2012-11-05 60 views
2

我有一個正則表達式,將與用戶的按鍵匹配。我很堅持。如何防止用戶使用jQuery在文本框中輸入特定字符?

這裏是我當前的代碼:

<script type="text/javascript"> 
    $('input.alpha[$id=tb1]').keydown(function (e) { 
     //var k = e.which; 
     //var g = e.KeyCode; 
     var k = $(this).val(); 
     //var c = String.fromCharCode(e.which); 
     if (k.value.match(/[^a-zA-Z0-9 ]/g)) { 
      e.preventDefault(); 
     } 
    }); 
</script> 

這裏的目的是爲了防止用戶輸入是正則表達式中的字符。

先生/女士您的回答會有很大的幫助。謝謝。

+2

「這裏是IE9的錯誤信息。」:在哪裏? –

+0

爲什麼'k.value',當'k = $(this).val()'?你檢查過重複嗎?我確信在SO上有很多類似的問題。請參閱[this](http://stackoverflow.com/q/2919898/944681),[this](http://stackoverflow.com/q/7543059/944681),[this](http://stackoverflow.com/q/2500620/944681)以及更多.. –

+0

我一直在調整代碼,這就是爲什麼它有點混亂。我想要做的是,如果用戶在鍵盤上按下了一個字符,並且它匹配正則表達式,它將防止默認值。 –

回答

3

嘗試使用fromCharCode方法:

$(document).ready(function() { 
    $('#tb1').keydown(function (e) { 

    var k = String.fromCharCode(e.which); 

    if (k.match(/[^a-zA-Z0-9]/g)) 
     e.preventDefault(); 
    }); 
}); 
+0

只有一個這個問題。它也會阻止退格鍵。 –

+0

@ MichaelS.Miller如果你想保留退格空間,只需在正則表達式中加'\ x08':'/ [^ a-zA-Z0-9 \ x08]/g'。 – Korikulum

2

您使用keypress而不是​​並阻止默認操作。

例如,這防止鍵入w到文本輸入:

$("#target").keypress(function(e) { 
    if (e.which === 119) { // 'w' 
    e.preventDefault(); 
    } 
}); 

Live Copy | Source

更新:如果它是應用該傳給你的麻煩正則表達式:

$("#target").keypress(function(e) { 
    if (String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]/)) { 
    e.preventDefault(); 
    } 
}); 

Live Copy | Source

相關問題