Lake
Lake

Reputation: 89

Textarea block accented letters and alt code symbols

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.

Upvotes: 0

Views: 1856

Answers (2)

showdev
showdev

Reputation: 29178

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>

Upvotes: 2

vlumi
vlumi

Reputation: 1319

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.

Upvotes: 1

Related Questions