我正在使用以下正则表达式来验证 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/