I'm trying to use a Regex to only allow letters, '-', and the backspace on input fields. I need to be able to use the left and right arrow keys and the delete key. I was attempting to do this with:
$("#input").keypress(function (e) {
var regex = new RegExp("^[a-zA-Z-\b]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if((!(e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 46))){
if(!regex.test(key)){
return false;
}
}
});
where I would check if the key is not the left arrow (37), right arrow (39), or the delete key (46), and then check if the key is not in the regex.
This works on IE and Chrome, however on Firefox the key codes 37 and 39 also correspond to ' and % respectively.
The key codes work on all of the browsers, the issue is that [on firefox only] if I allow for the arrows and delete keys it also allows for the ' and % characters.