PO Box Regular Expression Validation

前端 未结 11 2191
攒了一身酷
攒了一身酷 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 04:07

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

提交回复
热议问题