我试图阻止用户使用 JavaScript 在我的表单字段中输入 < 或 >。这是我到目前为止所拥有的:
$(document).on('keydown', function (e) {
regex = new RegExp("\<|>");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
它仍然允许那些字符,我该如何停止呢?
最佳答案
为什么要先翻译然后再进行正则表达式?我喜欢保持简单:
$(document).on('keypress', function (e) {
if ((e.which == 62) || (e.which == 60)) { // greater than or less than key pressed
e.preventDefault();
}
});
编辑添加:
基于@Samsquanch 反馈的替代条件:
if ((String.fromCharCode(e.which) == '>') || (String.fromCharCode(e.which) == '<')) { // greater than or less than key pressed
关于javascript - 防止用户在表单字段中输入 < 或 >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21311048/