Javascript 英国邮政编码验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13969461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript UK Postcode Validation
提问by dai.hop
Possible Duplicate:
UK Postcode Regex (Comprehensive)
可能重复:
英国邮政编码正则表达式(综合)
I have the following code for validating postcodes in javascript:
我有以下代码用于验证 javascript 中的邮政编码:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
return regex.test(postcode);
}
Tests:
测试:
CF47 0HW - Passes - Correct
CF47 OHW - Passes - Incorrect
I have done a ton of research but can't seem to find the definitive regex for this common validation requirement. Could someone point me in the right direction please?
我做了大量的研究,但似乎无法找到这个常见验证要求的明确正则表达式。有人能指出我正确的方向吗?
回答by paulgrav
Make your regex stricter by adding ^ and $. This should work:
通过添加 ^ 和 $ 使您的正则表达式更严格。这应该有效:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
}
回答by duncan
You want a 'definitive regex' - given all the permutations of the UK postcodes, it needs to be therefore 'unnecessarily large'. Here's one I've used in the past
您需要一个“明确的正则表达式”——鉴于英国邮政编码的所有排列,因此它需要“不必要地大”。这是我过去用过的
"(GIR 0AA)|((([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][ABCDEFGHJKSTUW])|([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY])))) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2})"
Notice I never just use A-Z, for instance, because in each part there are always certain letters excluded.
请注意,例如,我从不只使用 AZ,因为在每个部分中总会排除某些字母。
回答by Mark Withers
The problem is the first line of your function. By trimming the spaces out of the target string, you allow false positives.
问题是你的函数的第一行。通过修剪目标字符串中的空格,您可以允许误报。
CF47OHW will match [A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}
CF47OHW 将匹配 [AZ]{1,2}[0-9]{1,2} ?[0-9][AZ]{2}
CF matches [A-Z]
4 matches [0-9]{1,2}
(blank) matches \s?
7 matches [0-9]
OH matches [A-Z]{2}
W gets discarded
So, as Paulgrav has stated, adding the start and end characters (^ and $) will fix it.
因此,正如 Paulgrav 所说,添加开始和结束字符(^ 和 $)将修复它。
At that point, you can also remove the \s? bit from the middle of your regex.
此时,您还可以删除 \s? 来自正则表达式的中间。
However! Despite the bug being fixed, your regex is still not going to work how you'd like it to. You should look at the following rather good answer on this here site UK Postcode Regex (Comprehensive)
然而!尽管错误已修复,您的正则表达式仍然无法按照您的意愿工作。您应该在此站点上查看以下相当不错的答案UK Postcode Regex (Comprehensive)

