Textarea 块重音字母和 alt 代码符号

Textarea block accented letters and alt code symbols

我目前正在阻止 javascript 个字符代码,但它不会阻止重音字母和替代代码符号,例如 è、á、☺、♥ 等。

 $("#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;
    }
});  

我希望它不允许这些字符。

并非所有文本输入都会产生按键事件,尤其是在产生字符涉及多个按键时。

与其试图通过阻止输入事件来捕获非法字符,您还可以在输入元素已经插入后从输入元素中删除所有非法字符。

与其将您禁止的字符列入黑名单,不如考虑将您允许的字符列入白名单。我使用 input 事件取得了一些成功,seems to fire 即使在 ALT-key 组合之后(例如重音字母)。

下面只允许输入字母和数字。重音字母首先转换为 non-accented 个字母,但如果您不需要,可以删除该部分。

我从 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>