PO Box Regular Expression Validation
This is what i have used accounting for spaces and case insensitive:
http://regexr.com/3cc2q
var pattern = /\bP(ost|ostal)?([ \.]*(O|0)(ffice)?)?([ \.]*Box)\b/i;
- fail - po box
- fail - p.o. box
- fail - po bo
- fail - post office box
- fail - P.O. Box
- fail - PO. Box
- fail - PO Box
- fail - POBox
- fail - P O Box
- fail - P.O Box
- fail - PO
- fail - Postal Box
- fail - Post Office Box
- pass - poop box
- pass - pony box
With Javascript its easier to use a regex literal like so:
var pattern = /\b(?:p\.?\s*o\.?|post\s+office)\s+box\b/i;
(No backslashes required!)
In javascript, you have to escape your slashes:
var pattern = new RegExp('\\b[P|p]*(OST|ost)*\\.*\\s*[O|o|0]*(ffice|FFICE)*\\.*\\s*[B|b][O|o|0][X|x]\\b');
Also, you could reduce your pattern a bit by using case-insensitive matching:
var pattern = new RegExp('\\b[p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x\\b', 'i');
Note: Your regex also matches on addresses such as:
- 123 Poor Box Road
- 123 Harpo Box Street
I would suggest also checking for a number in the string. Perhaps this pattern from a previous answer would be of some help:
var pattern = new RegExp('[PO.]*\\s?B(ox)?.*\\d+', 'i');
(it won't match on "Post Office" spelled out, or the numeric replacements.. but it's a start.)
I tried several PO Box RegExp patterns found on the internet including the ones posted on Stack Overflow, none of them passed our test requirements. Hence, I posted our RegExp below and our test sets:
var poBox = /^ *((#\d+)|((box|bin)[-. \/\\]?\d+)|(.*p[ \.]? ?(o|0)[-. \/\\]? *-?((box|bin)|b|(#|n|num|number)?\d+))|(p(ost|ostal)? *(o(ff(ice)?)?)? *((box|bin)|b)? *(#|n|num|number)*\d+)|(p *-?\/?(o)? *-?box)|post office box|((box|bin)|b) *(#|n|num|number)? *\d+|(#|n|num|number) *\d+)/i;
var matches = [ //"box" can be substituted for "bin"
"#123",
"Box 123",
"Box-122",
"Box122",
"HC73 P.O. Box 217",
"P O Box125",
"P. O. Box",
"P.O 123",
"P.O. Box 123",
"P.O. Box",
"P.O.B 123",
"P.O.B. 123",
"P.O.B.",
"P0 Box",
"PO 123",
"PO Box N",
"PO Box",
"PO-Box",
"POB 123",
"POB",
"POBOX123",
"Po Box",
"Post 123",
"Post Box 123",
"Post Office Box 123",
"Post Office Box",
"box #123",
"box 122",
"box 123",
"number 123",
"p box",
"p-o box",
"p-o-box",
"p.o box",
"p.o. box",
"p.o.-box",
"p.o.b. #123",
"p.o.b.",
"p/o box",
"po #123",
"po box 123",
"po box",
"po num123",
"po-box",
"pobox",
"pobox123",
"post office box",
"Post Box #123"
];
var nonMatches = [
"The Postal Road",
"Box Hill",
"123 Some Street",
"Controller's Office",
"pollo St.",
"123 box canyon rd",
"777 Post Oak Blvd",
"PSC 477 Box 396",
"RR 1 Box 1020"
];