I have a regular expression that will be matched against the keypress of the user. I'm quite stuck with it.
Here is my current code:
<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>
The goal here is to prevent the user from typing characters that are inside the regex.
Try using the fromCharCode method:
$(document).ready(function () {
$('#tb1').keydown(function (e) {
var k = String.fromCharCode(e.which);
if (k.match(/[^a-zA-Z0-9]/g))
e.preventDefault();
});
});
You use keypress
rather than keydown
and prevent the default action.
For example, this prevents typing a w
into the text input:
$("#target").keypress(function(e) {
if (e.which === 119) { // 'w'
e.preventDefault();
}
});
Live Copy | Source
Update: If it's applying the regex that's giving you trouble:
$("#target").keypress(function(e) {
if (String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]/)) {
e.preventDefault();
}
});
Live Copy | Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With