Skip to content

PO Box Regular Expression Validation

Here’s my code, but I can’t ever trigger the alert.

$(document).ready( function (){
    $("[id*='txtAddress1S']").blur(function() {
        var pattern = new RegExp('b[P|p]*(OST|ost)*.*s*[O|o|0]*(ffice|FFICE)*.*s*[B|b][O|o|0][X|x]b');
        if ($("[id*='txtAddress1S']").val().match(pattern)) {
            alert('We are unable to ship to a Post Office Box.nPlease provide a different shipping address.'); 



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.)