View Single Post
Old 01-05-2013, 08:47 PM   PM User | #1
xelawho
Senior Coder

 
xelawho's Avatar
 
Join Date: Nov 2010
Posts: 2,461
Thanks: 52
Thanked 457 Times in 455 Posts
xelawho will become famous soon enoughxelawho will become famous soon enough
return false from nested $.each loop

hello,

I am trying to write an easily-customisable greasemonkey script that validates phone numbers. There can be any number of numbers for checking and any number of accepted formats (and I want it to be easy for non-coders to add formats). So I figured put the regexes in an object and loop through the input values, testing each regex against them.

The rules are:
if there is nothing in any of the inputs, no alert
if the number matches any of the formats, no alert

The script is working fine as is, but I don't know much about jQuery and I'm not sure if this is the correct/best way to break out of the loop (if valid) and alert that the number doesn't meet any of the criteria (if not).

Don't worry about the crappy poiphone string thing - I'm using that for something else, but it came in handy here as well.

Any suggestions welcomed. Like I say, it's greasemonkey so I can't do anything about class names and it has to work with jQuery 1.6.2

Code:
<head>
<script src="http://code.jquery.com/jquery-1.6.2.js"></script>	
</head>
<body>
<input class="number" value="5738-6969"/>
<input class="number" value="23-5738-6969"/>
<input class="number" value="538-6969"/>
<input class="number" value="2-5738-6969"/>
<input type="button" id="vali" value="validate"/>
<script type="text/javascript">
$(document).ready(function () {

$("#vali").click(function(){
    var poiphone = "";
    var telformats = {
        ph1: (/^(\d{4})-(\d{4})$/), //checks for format of phone number XXXX-XXXX
        ph2: (/^(\d{2})-(\d{4})-(\d{4})$/) //checks for format of phone number XX-XXXX-XXXX
    };
    $.each($(".number"), function () {
        var tel = $(this).val();
        if (tel != "") {
		poiphone += tel;
            var isValid = false;
            $.each(telformats, function () {
                if (this.test(tel)) {
                    isValid = true;
                    return;
                }
            });
            if (!isValid) {
                alert("Telephone " + tel + " is not a valid format")
            }
        }
    });

});
});
</script>
</body>

Last edited by xelawho; 01-05-2013 at 08:59 PM.. Reason: added button for easier testing
xelawho is offline   Reply With Quote