﻿$.validator.addMethod("phone", function(ph, element) {
    if (ph == null) {
        return false;
    }
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
    // 10 is the minimum number of numbers required
    return ((/\d{10,}/i).test(stripped));
}, "Please enter a valid phone number");

$.validator.addMethod("dropdown", function(value, element) {
    return this.optional(element) || element.selectedIndex > 0;
}, "Please make a selection from the list");

$.validator.addMethod("zipcode", checkZip($(this).val()), "Please specify a valid US ZIP code");

$.validator.addMethod("ziplist", function(value, element) {
    var ziparray = value.toString().split(",");
    for (i = 0; i < ziparray.length; i++) {
        if (!checkZip(ziparray[i]))
            return false;
    }
    return true;
}, "There is an invalid Zip Code in your Zip Code list");

function checkZip(zip) {
    // matches US ZIP code
    // allow either five digits or nine digits with an optional '-' between
    zip = zip.replace(/^\s+/, "");
    zip = zip.replace(/\s+$/, "");

    if (zip.length == 0) {
        return true;
    }

    if (zip.match(/^\d{5}([- ]?\d{4})?$/)) {
        return true;
    }
    return false;
}