用javascript验证字段中的键输入
Validate key input in field with javascript
我使用
document.getElementById('input-field').addEventListener('keyup', function (e) {
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
event.preventDefault();
}
});
它几乎工作。问题是我不能使用箭头键、退格键、删除键、ctrl+a键等。
我怎么能限制它只有那些键,将给出一个字符串表示在特定的输入?
要忽略这些键,您需要在验证输入之前添加一个条件。
例如,你可以创建一个数组,其中包含所有你想忽略的KeyCodes,并且只测试键入的键是否不在其中之一。
这是你需要的:
document.getElementById('input-field').addEventListener('keypress', function(e) {
//An array of special Keys
var specialKeys = [37, 38, 39, 40, 8, 13, 27, 46];
if (specialKeys.indexOf(e.which) === -1) {
console.log(String.fromCharCode(e.which)+ ' Key is validated!');
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
event.preventDefault();
}
}
});
<input type="text" id="input-field" placeholder="input text here">
注意:
正如在注释中提到的,您需要使用keypress
事件而不是keyup
来立即验证每个输入的字符。
这就限制了你的输入范围。但我认为在这种情况下,您正在寻找一种方法来识别仅可打印的关键事件。
你可以通过使用@TimDown提出的解决方案来实现这一点,如何检测按下的键是否会在<input>
文本框内产生一个字符?应用于keypress
事件,如下面的代码所示。因此,您可以只处理可打印的键事件。
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
document.getElementById('input-field').addEventListener('keypress', function (e) {
if(isCharacterKeyPress(e)){
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
e.preventDefault();
}
}
});
<input type="text" id="input-field" placeholder="input text here">
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 而循环只设置php中输入字段中的第一个值
- 在输入字段中将最小金额设置为
- 如何在输入字段中的按钮的帮助下打开日历,该字段的类型为“=”;日期”;
- 如何在HTML输入字段中添加不可删除的后缀
- 互斥单选按钮和相应的输入字段
- 在IE9中的输入字段中输入焦点最近按钮
- 选中单选框时将属性添加到输入字段
- 当设置addFromAutocompleteOnly时,剩余文本将保留在输入字段中
- 我如何在数字插入中使用逗号,这样它就不会'不要破坏我的输入字段
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 输入字段将't获取更新的值
- 如何选择多个输入字段并删除所需的属性
- 输入字段,只接受0到12之间的数字
- 单击鼠标,用MySQL数据填充html表单输入字段
- 使用jquery将输入字段转换为文本
- Model中的Typeahead返回空值以形成输入字段
- 如何从查询字符串中的输入字段发回文本
- 如何验证日期、月份和日期的3个独立输入字段;年使用jquery或javascript
- 将值传递给jquery创建的输入字段