Phone

by Evan Sharp

HTML

<input type="text" value="Enter Phone Number" title="Enter Phone Number" placeholder="Enter Phone Number" data-validate="phone" />

JavaScript

(function($){
    $.fn.phoneFormatter= function(){
        this.each(function(i,l){
            var $l = $(l);
            $l.change(function(){
                var num = $l.val().replace(/[^\d]/g,"");
                if(num.charAt(0) == "1" || num.charAt(0) == "0")
                    num = num.substr(1);
                if(num.length != 10)
                    alert("Please enter a valid phone number\nThis will be replaced with the UI for invlaid fields");
                else
                    $l.val(num.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"));
            }).keydown(function(e){
                if(e.keyCode >= 65 && e.keyCode <= 90)
                    return false;
            });
        });
        return this;
    }
})(jQuery);
        
$("[data-validate='phone']").phoneFormatter();