prevent typing non ascii characters in a textbox(防止在文本框中输入非 ascii 字符)
问题描述
因为我认为人们在我之前已经遇到了很多时间,并且可能有一些标准的解决方案.. 任何人都可以给出任何提示方向如何防止用户在文本框中输入非 ascii 字符.
Since I think people have encounter it lots of time before I did and there may be some standart solution.. Can anybody give any hint direction how to prevent a user from typing non ascii characters in a textbox.
推荐答案
我个人觉得修改标准交互模式有点烦人,但是如果你必须过滤键盘输入,你可以通过拦截按键事件并取消那些你不想要的:
I personally find tinkering with standard modes of interaction a bit annoying, but if you must filter keyboard input, you can do it by intercepting key press events and canceling the ones that you don't want:
var allowed = /[a-zA-Z0-9]/; // etc.
window.onload = function () {
var input = document.getElementById("test");
input.onkeypress = function () {
// Cross-browser
var evt = arguments[0] || event;
var char = String.fromCharCode(evt.which || evt.keyCode);
// Is the key allowed?
if (!allowed.test(char)) {
// Cancel the original event
evt.cancelBubble = true;
return false;
}
}
};
而且使用 jQuery 更简洁漂亮:
And it's more concise and prettier with jQuery:
var allowed = /[a-zA-Z0-9]/; // etc.
$(function () {
var input = document.getElementById("test");
$("#input").keypress(function (e) {
// Is the key allowed?
if (!allowed.test(String.fromCharCode(e.keyCode || e.which))) {
// Cancel the original event
e.preventDefault();
e.stopPropagation();
}
});
});
这篇关于防止在文本框中输入非 ascii 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:防止在文本框中输入非 ascii 字符
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01