我需要验证字符串只包含字母,数字最多为4,'。'和' _';
现在我正在使用
if(/^[a-zA-Z0-9_.]+$/.test(testString))
{
console.log("Valid string");
}
testString = test.com // (must be valid)
testString = Te_St.com // (must be valid)
testString = Te_St1.com // (must be valid)
testString = Te_St12.com // (must be invalid because has 12 in it and is higher than 4)
testString = Te_2St1.com // (must be valid)
testString = Te_24St1.com // (must be invalid because has 24 in it and it higher than 4)
testString = Te_2$St1.com // (must be invalid because has ilegal character $)
答案 0 :(得分:2)
您可以尝试以下模式:
/^[a-z._]*(?:[01234](?:[a-z._]+|$))*$/i
但请注意,此模式使用空字符串成功。为了防止这种情况,您可以在模式开始之前测试字符串长度或添加前瞻:
/^(?=.)[a-z._]*(?:[01234](?:[a-z._]+|$))*$/i
答案 1 :(得分:1)