我是一名初学者,正在编写JQuery以添加到自定义表单网站。大多数选项都是拖放,但在某些情况下我必须编写自定义jquery。
为此,我已经能够找出验证九个字符的字符串,以便在字符串长度不超过9个字符时显示错误消息,并且如果它以&#34以外的任何字符串开头; B"," E"或" N。"
但是,它还需要检查并确保第一个之后的所有其他字符都是数字。例如,可接受的用户输入将是e00012345。
最简单的方法是什么?
// this validation will check to make sure that an accepted value is entered into a field.
// currently, the validation is not perfect. Ideally, the value would start with a specific character (n, b or e) and 8 digits. Right now it just must start with n, b or e and be 9 characters long.
$(function() {
// for the Missouri Business Number -- on blur, if the value is 9 characters long and starts with b, e, or n (uppoer or lower case), then the input is valid. Otherwise, error messages appear.
$("input#id_wrT4duNEOW").blur(function() {
if (
(($("#id_wrT4duNEOW").val().startsWith("b")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("e")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("n")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("B")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("E")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("N")) &&
($("#id_wrT4duNEOW").val().length == 9))
)
{
// good things happen
}
else {
// error message
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
修改
好的,我尝试添加正则表达式行,但我没有得到结果。我错过了什么?
$(function() {
$("input#id_wrT4duNEOW").blur(function() {
const regex = /^[bBeEnN]{1}[0-9]{8}$/
var mobiz = $("#id_wrT4duNEOW").val();
if (console.log(regex.test(mobiz)))
{
// good things happen
}
else {
// error message
}
});
});
答案 0 :(得分:1)
正规救援。使用正则表达式及其相关的.test
方法非常简单。以下正则表达式确保字符串以字符b
,e
或n
之一(不区分大小写)开头,后跟正好8位数字:
test1 = "B12345678";
test2 = "N123456789";
test3 = "x12345678";
const regex = /^[bBeEnN]{1}[0-9]{8}$/
console.log(regex.test(test1))
console.log(regex.test(test2))
console.log(regex.test(test3))
因此,对于您的代码段,您可以像这样调整它:
$(function() {
$("input#id_wrT4duNEOW").blur(function() {
var val = $("#id_wrT4duNEOW").val();
if (/^[ben]{1}\d{8}$/i.test(val)) {
// good things happen
} else {
// error message
}
});
});
答案 1 :(得分:0)
//1) must be 9 characters
//2) first character must be B, E, or N
//3) 8 characters past the first must be digits
var pattern = /^(B|E|N)\d{8}$/
console.log(pattern.test("weee"));
console.log(pattern.test("B12345678"));
console.log(pattern.test("A12345678"));
console.log(pattern.test("B123456789"));
&#13;