gpt4 book ai didi

javascript - 防止用户在表单字段中输入 < 或 >

转载 作者:搜寻专家 更新时间:2023-11-01 05:12:05 25 4
gpt4 key购买 nike

我试图阻止用户使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com