我有一个输入字段,我想在其中只允许数字和一个逗号。我怎么才能让它只接受一个逗号呢?
$("#my-field").on("keyup", checkKey);
function checkKey() {
this.value = this.value.replace(/[^0-9,]/g, "");
}
发布于 2017-02-22 06:39:20
你可以这样做:
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "")
.replace(/(,.*?),(.*,)?/, "$1");
// don't move cursor to end if no change
if (clean !== this.value) this.value = clean;
}
// demo
document.querySelector('input').oninput = checkKey;
<input>
这将删除所有重复的逗号,以及它们之间的所有内容。这不是问题,因为你一次只按一个键。
备注
这种输入验证的阻塞方式对用户不友好。给东西涂上颜色,或者把信息放进去,总比让键盘失灵要好。
考虑使用<input type="number">
元素,它内置了数字验证。
在检查input
中的更改时,input
事件通常比keyup
更有用,因为也可以通过鼠标操作和上下文菜单进行更改。
如果您希望允许使用点而不是逗号,那么请在正则表达式中使用\.
更改每个,
,因为.
在正则表达式中有特殊含义,必须进行转义才能作为文字字符。
https://stackoverflow.com/questions/42379057
复制相似问题