0

I'm currently blocking javascript character codes but it doesn't block accented letters and alt code symbols such as è,á,☺,♥ and etc.

 $("#cstedit-addembossing").keypress(function(e) {

    var key = e.which;
    if(key > 32 && (key < 48 || key > 57) &&(key < 65 || key > 90) && (key < 97 || key > 122)) {
        return false;
    }
});  

I'd like it to not allow those characters.

Lake
  • 89
  • 8
  • 1
    A different method might be to only allow certain characters. [This answer](https://stackoverflow.com/a/36600951/924299) might be helpful. – showdev Jun 11 '19 at 01:08
  • @showdev I've tried that before, had trouble with it. Even though I only allowed a-z0-9 stuff like !@#$ still showed up – Lake Jun 11 '19 at 01:22

2 Answers2

2

Instead of blacklisting characters you prohibit, consider whitelisting characters you allow. I had some success using the input event, which seems to fire even after ALT-key combinations (like for accented letters).

Below, only letters and numbers are allowed. Accented letters are first converted to non-accented letters, but you can remove that part if you don't want it.

I got the code for converting accented characters from Lewis Diamond's answer here.

$('#cstedit-addembossing').on('input', function() {

  let $this = $(this);

  let newVal = $this.val()
    .normalize('NFD').replace(/[\u0300-\u036f]/g, "")
    .replace(/[^0-9A-Za-z]+/g, '');

  $this.val(newVal);

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="cstedit-addembossing"></textarea>
showdev
  • 28,454
  • 37
  • 55
  • 73
1

Not all text input produces keypress events, in particular if producing the character involves more than one key.

Instead of trying to catch the illegal characters by blocking the input event, you could instead just remove any illegal characters from the input element after it's been inserted there already.

vlumi
  • 1,321
  • 1
  • 9
  • 18