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 字符
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
