gpt4 book ai didi

javascript - 如果模式针对正则表达式,则防止继续在文本框上书写

转载 作者:行者123 更新时间:2023-11-30 20:56:30 25 4
gpt4 key购买 nike

我的护照代码有一个文本框

如果用户输入的代码与正则表达式不同,我该如何定义以防止继续在文本框上书写?

并保留错误直到用户输入正确的错误?这是我的片段:

$(".passno").each(function(index, element) {
$(this).bind('keyup', function(event) {
var regex = new RegExp("^[A-Z][0-9]{8}$");
var value = event.currentTarget.value;
if (!regex.test(value)) {
$(this).next(".box-infoes").find(".error").css("display", "block")
} else {
$(this).next(".box-infoes").find(".error").css("display", "none")
}

});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" class="passno" placeholder="e.g.=J12345678" />
<div class="box-infoes">
<div style="color:red; display:none;" class="error"> This Is a Wrong passportcode !</div>
</div>

最佳答案

你的正则表达式应该像 RegExp("[A-Z]{1}[0-9]{8}") 但你的代码需要更多修改,这样可以防止一些按钮像 SHIFT CTRLAS 字符或如果它为空则删除错误等。

现在正则表达式说:[A-Z]{1} 一个字 + [0-9]{8} 八个数字。

示例类型 J12345678

$(".passno").each(function(index, element) {
$(this).bind('keyup', function(event) {
var regex = new RegExp("[A-Z]{1}[0-9]{8}");
var value = event.currentTarget.value;
$(this).val($(this).val().toUpperCase());

if (!regex.test(value) || value.length > 9) {
$(this).next(".box-infoes").find(".error").css("display", "block")
} else {
$(this).next(".box-infoes").find(".error").css("display", "none")
}

});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" class="passno" placeholder="e.g.=J12345678" maxlength="9"/>
<div class="box-infoes">
<div style="color:red; display:none;" class="error"> This Is a Wrong passportcode !</div>
</div>

好吧,为了限制字符长度,您可以在 input 上使用 maxlength="9" 或使用 jquery value 控制它.length > 9

关于javascript - 如果模式针对正则表达式,则防止继续在文本框上书写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47605117/

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