Javascript正则表达式匹配5或9位数的邮政编码 [英] Javascript Regular Expression to match 5 or 9 digit zipcode
问题描述
我有一个与我最近的帖子类似的问题,但有一个邮政编码验证器,我试图转换为javascript验证过程。我的脚本如下:
I have a similar issue as my recent post but with a zip code validator i am trying to convert over to a javascript validation process. my script looks like so:
var regPostalCode = new RegExp("\\d{5}(-\d{4})?");
var postal_code = $("input[name='txtzipcode']").val();
if (regPostalCode.test(postal_code) == false) {
bValid = false;
msg = msg + '<li>Invalid Zip Code.</li>';
}
从我最近的帖子中我了解到我在开始时需要的转义字符。基本上这个函数验证的是一个22621的邮政编码是正确的,但它不应该验证22601-1。破折号后应该有2位数字,如22601-9999。这就像验证的第二部分总是如此。这个表达对我来说再次起作用。我错过了什么吗?是否需要另一个转义字符?
From my recent post I learned of the escape character that I needed at the beginning. Basically this function is validating a zip code that is say 22601 which is correct, but it shouldn't validate 22601-1. There should have to be 4 digits after the dash like 22601-9999. It's like the second part of the validation is always true. Again this expression has worked in the past for me. Am I missing something? Is another escape character needed?
推荐答案
添加锚点:新的RegExp(^ \\d {5}( - \\d {4})?$)
。这会强制正则表达式引擎仅接受匹配,如果它从字符串的第一个字符开始( ^
)并在字符串的结尾处结束( $
)匹配。
Add anchors: new RegExp("^\\d{5}(-\\d{4})?$")
. This forces the regular expression engine to only accept a match, if it begins at the first character of the string (^
) and ends at the end of the string ($
) being matched.
注意,您在问题中给出的正则表达式中可能存在拼写错误:第二个 \d
缺少一个反斜杠。
Note, that there might be a typo in the regular expression you hav given in your question: the second \d
is missing a backslash.
这篇关于Javascript正则表达式匹配5或9位数的邮政编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!