“拦截”用户在文本框中输入内容并将其删除
我有一个文本框,我想对其进行一些验证。目前我有这样的代码:
function updateChanger() {
// Validate input
var likeMessage = validateInput($("#like").val());
alert(likeMessage);
}
function validateInput(input) {
input = input.replace(/[^a-zA-Z0-9:\(\/\)\s\.,!~]/g, "");
return input;
}
这成功地删除了 likeMessage 变量中不需要的字符,但该字符仍然被输入到文本框中。我想阻止这种情况发生。
我知道它与 $("#like").val()
有关,但我唯一能想到的就是从文本框值中删除结束字符,这会吗够了吗?
感谢您的帮助!
I have a text box that I would like to do some validation on. At the moment I have this code:
function updateChanger() {
// Validate input
var likeMessage = validateInput($("#like").val());
alert(likeMessage);
}
function validateInput(input) {
input = input.replace(/[^a-zA-Z0-9:\(\/\)\s\.,!~]/g, "");
return input;
}
This successfully trims out unwanted characters in the likeMessage variable, but the character still gets entered into the text box. I would like to stop that from happening.
I know it will have something to do with $("#like").val()
but the only thing I can think of is just chopping off the end character from the text box value, would this suffice?
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
keyup
事件 来完成此操作,如下所示:这会检查并在每次按键时删除无效字符,因此无效字符永远不会留在框中,它会立即删除。
You can do it using the
keyup
event, like this:This checks for and removes invalid characters every time they key lets up, so the invalid character won't ever be left in the box, it gets removed immediately.