Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery PO BOX validation

Tags:

jquery

regex

I have looked through some of the older posts and still a little confused with what is happening. I have a shipping form that DOES NOT allow PO Boxes so I am trying to find a validator to look through and make sure that input field doesn't have PO in it. I am making sure every field is filled out with this code but wondering how I could incorporate in the PO box validation with it. Note: this is a separate file from my actual form

$( document ).ready(

    function()
    {
        $( '#shipping' ).submit(
            function()
            {

                    var required_fields = new Array(
                        'name',
                        'service',
                        'company',
                        'contact',
                        'street',
                        'city',
                        'state',
                        'zip',
                        'projectnum'
                    );
                    
                            
                        for( j in required_fields )
                        {
                                            
                            var theRequiredField = required_fields[j]
                            var inputField = $( '[name="' + theRequiredField + '"]' )
                                            
                            if( inputField.val() == '' )
                            {                                   
                                alert( "The '" + theRequiredField + "' field is required." );
                                inputField.focus();
                                return false;
                                    
                            } 

                        } 
                        
                                                                
            } // function
            ) // submit
    }
                
);  
like image 896
Mike Jones Avatar asked Oct 28 '25 03:10

Mike Jones


2 Answers

There may be a better method, but here's what I came up with:

Live Demo

$('input[name=address]').each(function() {
    var pattern = new RegExp('[PO.]*\\s?B(ox)?.*\\d+', 'i');
    if ($(this).val().match(pattern)) {
        $(this).after('<span class="pob">No PO Boxes</span>');
    }
});
like image 95
drudge Avatar answered Oct 30 '25 14:10

drudge


I used the RegEx provided above by drudge. It works for most cases, but it gave me false positive for strings like "1122 new space – Apt. 99B1". So I modified RegEx to:

var pattern = new RegExp('(P.O.|PO|Box)+\\s?.*\\d+', 'i');

This one checks for either of "P.O." or "PO" or "Box" words, followed by a number to determine it as PO Box address.

like image 43
Mihir Kagrana Avatar answered Oct 30 '25 14:10

Mihir Kagrana