gpt4 book ai didi

jquery - 仅允许字母数字值

转载 作者:行者123 更新时间:2023-12-03 21:32:10 25 4
gpt4 key购买 nike

Possible Duplicate:
How to prevent users from entering invalid characters inside an input field

我在一个页面上有 3 个文本框。其中之一应允许数字,其他字母应允许,第三个应允许数字或字母。

由于这是唯一的要求,我不想使用验证插件或任何其他第三方插件。我怎样才能通过使用纯 jQuery 创建自己的插件来做到这一点?

这就是我所做的,但我感觉代码会变得太长

 $(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});

http://jsfiddle.net/Cvus8/

谁能告诉我解决这个问题的最佳方法是什么?

最佳答案

更好的解决方案可能是使用基于正则表达式的检查。下面的示例将限制 id text 字段中仅包含字母数字字符:

$('#text').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}

e.preventDefault();
return false;
});

关于jquery - 仅允许字母数字值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13236651/

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