Here’s my code, but I can’t ever trigger the alert.
JavaScript
x
10
10
1
$(document).ready( function (){
2
$("[id*='txtAddress1S']").blur(function() {
3
var pattern = new RegExp('b[P|p]*(OST|ost)*.*s*[O|o|0]*(ffice|FFICE)*.*s*[B|b][O|o|0][X|x]b');
4
if ($("[id*='txtAddress1S']").val().match(pattern)) {
5
alert('We are unable to ship to a Post Office Box.nPlease provide a different shipping address.');
6
}
7
8
});
9
});
10
Advertisement
Answer
In javascript, you have to escape your slashes:
JavaScript
1
2
1
var pattern = new RegExp('\b[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*\.*\s*[B|b][O|o|0][X|x]\b');
2
Also, you could reduce your pattern a bit by using case-insensitive matching:
JavaScript
1
2
1
var pattern = new RegExp('\b[p]*(ost)*\.*\s*[o|0]*(ffice)*\.*\s*b[o|0]x\b', 'i');
2
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:
JavaScript
1
2
1
var pattern = new RegExp('[PO.]*\s?B(ox)?.*\d+', 'i');
2
(it won’t match on “Post Office” spelled out, or the numeric replacements.. but it’s a start.)