gpt4 book ai didi

javascript - 如何在 jquery 中验证第一个字母而不是数字

转载 作者:行者123 更新时间:2023-12-03 02:42:48 25 4
gpt4 key购买 nike

我已经在 jquery 中编写了一个仅检查数字的验证规则,现在我想添加新的验证规则是 jquery 中的前三位字母,然后是 6 位数字。我怎样才能做到这一点。这是我唯一的数字验证代码。

$(".mrn").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}

最佳答案

我认为在按下按钮时检查按下的字符是否有效是不明智的。最好在用户完成输入并离开 DOMElement 时检查一次:

$(".mrn").focusout(function()
{
//Assuming the .mnr class is also the textbox:
var input = $(this).val();
var regex = /^\w{3}\d{6}$/; //match against the described pattern.
if (!regex.test(input)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
return true;
});

这样用户就可以自己输入错误并更正,维护逻辑所需的代码要少得多,而且性能也得到了更好的调整。

关于javascript - 如何在 jquery 中验证第一个字母而不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48249239/

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