Search code examples
phpregexlaravelvalidationlaravel-validation

Regex validate address string to not contain PO Box patterns


I'm using Laravel regex validation on the address field provided by users.

I found multiple posts that help to validate address string to be a valid PO Box like here or here, but I need to do the opposite and make sure the provided string is not a PO Box.

PS I don't need to do any address validation, just wanna make sure its anything but a PO Box.

I found this rule pretty useful since it checks for po box number to be present

/^\s*(.*((p|post)[-.\s]*(o|off|office)[-.\s]*(b|box|bin)[-.\s]*)|.*((p|post)[-.\s]*(o|off|office)[-.\s]*)|.*((p|post)[-.\s]*(b|box|bin)[-.\s]*)|(box|bin)[-.\s]*)(#|n|num|number)?\s*\d+/i

Can someone help me to create opposite expression for this one or anything similar?

I suspect I have to use negative lookahead ?!


Solution

  • Solved it by using regex negative lookahead ?!

    /^(?!.*(?:(.*((p|post)[-.\s]*(o|off|office)[-.\s]*(box|bin)[-.\s]*)|.*((p |post)[-.\s]*(box|bin)[-.\s]*)))).*$/i
    

    This rule does not require po box number to be present.

    Those are examples that will pass:

            "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",
            "Coop services",
            "65 Brook Ave Ste 1P",
            "pacific city",
            "orange county",
            "obox",
            "pbox",
            "party house",
            "p shorty",
            "something pacif pobo",
            "po helpkline box",
            "po ferrirs",
            "panther boxing",
            "box center",
            "post office",
            "Post",
            "porceline"
    

    Those will fail the validation

            "post office box",
            "POBOX",
            "po box",
            "POBox12234",
            "p o box",
            "P.O.Box",
            "HC73 P.O. Box 217",
            "P O Box125",
            "P. O. Box",
            "P.O. Box 123",
            "P.O. Box",
            "PO Box N",
            "PO Box",
            "PO-Box",
            "POBOX123",
            "Po Box",
            "Post Box 123",
            "Post Office Box 123",
            "Post Office Box",
            "p box",
            "p-o box",
            "p-o-box",
            "p.o box",
            "p.o. box",
            "p.o.-box",
            "po box 123",
            "po box",
            "po-box",
            "pobox",
            "pobox123",