我还是 javascript 新手,我正在尝试验证我的表单。我的输入之一是身份号码的文本输入,它遵循以下模式:####XX
其中# 代表一个数字,X 代表来自 AZ 的大写字母。
到目前为止,这是我的代码:
var IDnum = document.getElementById('identityNumber').value;
if ( (isNaN(IDnum.charAt(0))) && (isNaN(IDnum.charAt(1)))&& (isNaN(IDnum.charAt(2))) && (isNaN(IDnum.charAt(3))) && (!isNaN(IDnum.charAt(4))) )
{
document.getElementById('identityError').style.display = "inline-block";
}
else
{
document.getElementById('identityError').style.display = "none";
}
我试图用谷歌搜索它并看到了一些他们使用 RegExp 的信息,但是我还没有学到任何类似的东西。
使用上面的代码,无论我输入什么,它仍然会验证它。任何想法我做错了什么,是否有更简单和更简单的方法?
编辑:在寻找正则表达式和类似的答案后
^\d{4}[A-Z]{2}$
也没有用
您可以使用正则表达式来识别字符串是否在字符前有 4 位数字。
每个\d
代表一个数字,\d\d\d\d
表示 4 位数字(或者\d{4}
)。
后跟.
表示 4 位数字后跟任何字符。
function isAllowed(str) {
return str.match(/^\d\d\d\d.$/g) !== null
}
console.log(isAllowed("1234X"));
console.log(isAllowed("123a"));
console.log(isAllowed("3892#"));
console.log(isAllowed("X"));
var IDnum = document.getElementById('identityNumber').value;
if (isAllowed(IDnum))
{
document.getElementById('identityError').style.display = "inline-block";
}
else
{
document.getElementById('identityError').style.display = "none";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句