Javascript to check for PO boxes

It’s not pretty, but sometimes you need to check an address input to see if it’s a PO box.  Rules will be different around PO boxes.

For that, I use a simple javascript pattern.  It has the down side of checking for “P”, “O”, and “Box” in the string in order, so something like Poratable Box Road will fail validation, but I don’t think that’s a real road, so it seems to work for real world use cases.

var street1 = jQuery('#address1').val();
var street2 = jQuery('#address2').val();

var pattern = new RegExp('\\b[p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x\\b', 'i');

if(street1.match(pattern) || street2.match(pattern) {
    alert('We do not ship to PO boxes.  Please enter a different address");
    return false;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *