阻止用户在表单字段中输入
16lz
2021-01-22
I'm trying to prevent users from entering < or > into my form fields using JavaScript. Here's what I have so far:
我正在尝试阻止用户使用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;
}
});
It's still allowing those characters, how do I stop this?
它仍然允许这些角色,我该如何阻止它?
2 个解决方案
#1
5
Why bother translating then regexing? I like to keep it simple:
为什么要费心翻译呢?我喜欢保持简单:
$(document).on('keypress', function (e) {
if ((e.which == 62) || (e.which == 60)) { // greater than or less than key pressed
e.preventDefault();
}
});
Edit to add:
编辑添加:
Alternate if condition based on @Samsquanch feedback:
如果条件基于@Samsquanch反馈,则替换:
if ((String.fromCharCode(e.which) == '>') || (String.fromCharCode(e.which) == '<')) { // greater than or less than key pressed
更多相关文章
- 如何在选择单选按钮时显示文本字段
- 将输入文本字段显示为纯文本
- 在用户将'n'粘贴复制到文本字段后,如何更新视图模型?
- 带有无线电的JavaScript条件字段不起作用
- 如何在onchange()事件后调用的方法中将焦点设置为输入字段?
- 无法在JQuery中查找表单输入
- 用于转换单位的HTML和JavaScript表单
- jQuery表单验证Validata
- 在Javascript中将下拉字段乘以文本字段