JavaScript 正则表达式邮政编码验证问题

标签 javascript regex

我正在使用以下正则表达式来验证 5 位邮政编码。但它不起作用。

var zipcode_regex = /[\d]{5,5}/;
if (zipcode_regex.test($.trim($('#zipcode').val())) == false)
alert('invalid zipcode');

我还在代码片段中使用了 jQuery。

最佳答案

如果字符串中某处有一个五位数的子字符串,您的正则表达式也会匹配。如果你想验证“只有五个数字,没有别的”,那么你需要 anchor你的正则表达式:

var zipcode_regex = /^\d{5}$/;
if (zipcode_regex.test($.trim($('#zipcode').val())) == false)
    alert('invalid zipcode');

而且您可以更轻松地获得它:

if (!(/^\s*\d{5}\s*$/.test($('#zipcode').val()))) {
    alert('invalid zipcode');
}

关于JavaScript 正则表达式邮政编码验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10513623/

相关文章:

java - XML 中的通配 rune 件匹配

regex - 是否可以使用简单的REGEX过滤“lava_rapido”和“lava-rapido”?

C++ boost 正则表达式 : How to find all possible string constants from C/C++ code?

javascript - 将鼠标悬停在其他页面元素上时更改点样式

javascript - 大约 5 天后,IOS 应用程序在启动画面上崩溃

javascript - google map api 调整 map 大小

python - 在mysql加载数据文件导入期间删除CSV公式值

javascript - 为什么 [.\n]+ 不匹配字符串 'a\nb' ?

javascript - 如何在 selenium 中使用 WebElementPromise

regex - VBA webscraper - 使用正则表达式返回 InnerHTML