3

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.

parrigin777
  • 178
  • 1
  • 1
  • 10
  • 1
    keyCode is a number, not sure why you have them as strings. – epascarello Jan 18 '18 at 15:37
  • 1
    Possible duplicate of [JavaScript keycodes are not working in Firefox](https://stackoverflow.com/questions/44449946/javascript-keycodes-are-not-working-in-firefox) – revo Jan 18 '18 at 15:38
  • I looked into that answer. It's not that the keycodes aren't working on Firefox, it's that they allow the arrow/delete keys AND the ' and % characters. I need just the arrow/delete keys to work. – parrigin777 Jan 18 '18 at 16:25

1 Answers1

0

I was actually able to figure it out. For IE and Chrome the keyCode and Which values are the same. On Firefox the keyCode value of the left arrow is 37, but the which value is 0.

I was able to solve it doing this:

$("#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.which == 0) || (e.keyCode == 39 && e.which == 0) || (e.keyCode == 46 && e.which == 0))){
      if(!regex.test(key)){
         return false;      
      }        
   }
});
parrigin777
  • 178
  • 1
  • 1
  • 10