Block users from entering double-byte characters in textboxes [closed]

半城伤御伤魂 提交于 2020-01-07 08:46:31

问题


I want users to prevent entering double-byte characters in input fields. Following code will allow users to enter a-z or A-Z. I want users to prevent entering double-byte characters like Korean, Chinese etc. But users should be allowed to enter Spanish characters since those are not double-byte characters. This should work when user copy-paste double-byte characters.

$("#myTextBox").bind("keypress", function(event) { 
        var charCode = event.which;
        var keyChar = String.fromCharCode(charCode); 
        return /[a-zA-Z]/.test(keyChar); 
    });

回答1:


Technically, you can set a pattern attribute and list all characters that are allowed, like this:

<input pattern="^[-a-zA-Z0-9 äÄöÖüÜßẞÇçâêîôûàèùéêëïü]*$" />

or, if you want to allow all unicode characters in the range up to and including Arabic:

<input pattern="^[ -&#2303;]+$" />

Note that both solutions leave out some characters that non-Asian users may use, for instance in the first pattern Scandinavian characters like å or ø and in the second pattern the upper-case ẞ, Emoji, and more. If you can classify the 100000+ characters in the Unicode standard, you can simply list all allowed in the pattern.

A pattern allows typing the characters, but you can use the :invalid CSS class to give appropriate feedback. If you really want to delete the characters, you can clean them, like this (live demo):

input.addEventListener('input', () => {
    var allowed_m = /\[([^\]]*)\]/.exec(input.pattern);
    var negative_pattern = new RegExp('[^' + allowed_m[1] + ']', 'g');
    input.value = input.value.replace(negative_pattern, '');
}

Any of these solutions are user-hostile though. You will almost certainly miss corner cases (already here: is Arabic an Asian language? Are characters that occur in Asian languages and also non-Asian languages forbidden?), and users from all around the world will be frustrated about the experience on your website.

Instead, fix the code that deals with exotic characters, and explain to the user why Latin characters are preferred.



来源:https://stackoverflow.com/questions/48885596/block-users-from-entering-double-byte-characters-in-textboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!