0

The following blocks out all chars which are not either alphabetic or backspace (\b), but you can see that the Backspace doesn't work and is also filtered out. Why is that?

$('#field').keydown(function(e) {
  if (!/^[A-Za-z\b]$/i.test(e.key)) {
    e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="field" />
gene b.
  • 10,512
  • 21
  • 115
  • 227
  • `[A-Za-z\b]` doesn't this have the backspace char in the class ? Have you tried `[A-Za-z\x08]` ? Or possibly even `if (/^[^A-Za-z\x08]$/i.test(e.key))` Because nothing says bogus like when regex doesn't support the backspace control character.. – sln Jul 13 '23 at 20:32
  • witness: https://regex101.com/r/HWh8Ea/1 https://regex101.com/r/MssBzT/1 – sln Jul 13 '23 at 20:47

1 Answers1

1

The event.key value for the backspace key is "Backspace".

$('#field').keydown(function(e) {
  if (!/^([a-z]|Backspace)$/i.test(e.key)) {
    e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="field" />
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • But inside character classes `\b` is a backspace: https://stackoverflow.com/a/17438159/1005607 . This is used inside a character class, isn't it? – gene b. Jul 13 '23 at 20:15
  • 1
    @geneb. That's true, but `event.key` is not a literal backslash character for backspace, but the string `"Backspace"`. – Unmitigated Jul 13 '23 at 20:16
  • Ah, so that was the issue. thanks. – gene b. Jul 13 '23 at 20:17
  • @geneb. Happy to help. – Unmitigated Jul 13 '23 at 20:18
  • One more question. I need to allow all navigation chars: Backspace, Delete, Arrow Keys, and Home and Delete. In other words, all alphabetic + navigation, but nothing else. Is there a simple way to accomplish this? Or do I have to enumerate each key? – gene b. Jul 13 '23 at 20:24
  • 1
    @geneb. Unfortunately, you would have to list out the keys apart from the alphabetic ones. – Unmitigated Jul 13 '23 at 20:28
  • And yet another MS imposed penalty, or is it? The only way. Might as well jump off a cliff. – sln Jul 13 '23 at 21:22