PO Box Regular Expression Validation

前端 未结 11 2199
攒了一身酷
攒了一身酷 2020-12-05 03:19

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

$(document).ready( function (){
    $(\"[id*=\'txtAddress1S\']\").blur(function() {
        var pattern         


        
11条回答
  •  长情又很酷
    2020-12-05 03:52

    We ran into false positive PO Boxes after using @Dathan's answer in production for a few months. This simplified version ensures the pattern is followed by a number so won't match things like "Expo Blvd". It also allows things like "#123" and "B1" commonly found in address2 fields for apartment/unit/suite numbers. You can play around with it and add your own test cases here: https://regex101.com/r/7ZUQFl/2

    const re = /^\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;
    const matches = [
      "post office box 1",
      "post office b 1",
      "post off box 1",
      "post off b 1",
      "post o box 1",
      "post o b 1",
      "p office box 1",
      "p office b 1",
      "p off box 1",
      "p off b 1",
      "p o box 1",
      "p-o-b-1",
      "p.o.b.1",
      "POB1",
      "pob #1",
      "pob num1",
      "pob number1",
      "foo pob1",
      "box #1",
      "po 1",
      "pb 1"
    ];
    const nonMatches = [ 
      "Expo Blvd",
      "Rural Route Box 1",
      "Army Post 1",
      "B1",
      "#1",
      "N1",
      "Number 1",
      "Num 1"
    ];
    

提交回复
热议问题