阻止用户在文本框中输入双字节字符 [英] Block users from entering double-byte characters in textboxes

查看:197
本文介绍了阻止用户在文本框中输入双字节字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户阻止在输入字段中输入双字节字符.以下代码将允许用户输入a-z或A-Z.我希望用户避免输入韩文,中文等双字节字符.但是应允许用户输入西班牙字符,因为这些字符不是双字节字符.当用户复制粘贴双字节字符时,此方法应该起作用.

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); 
    });

推荐答案

从技术上讲,您可以设置

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

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

或者,如果您想允许所有unicode字符,包括阿拉伯文,包括以下范围:

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

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

请注意,这两种解决方案都忽略了非亚洲用户可能使用的某些字符,例如,在第一个模式的斯堪的纳维亚字符(如å或ø)中,以及在第二个模式的大写字母ẞ,Emoji等.如果您可以将Unicode标准中的100000+个字符分类,则只需列出该模式中允许的所有字符即可.

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.

模式允许键入字符,但是您可以使用:invalid CSS类来提供适当的反馈.如果您确实要删除字符,可以像这样清理它们(实时演示):

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.

这篇关于阻止用户在文本框中输入双字节字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆