Javascript phone mask for text field with regex

前端 未结 2 614
北荒
北荒 2021-01-26 12:36

I\'m using this function to phone mask and works almost perfectly.

function mask(o, f) 
{ 
    v_obj = o; 
    v_fun = f; 
    setTimeout(\"execmask()\", 1) 
};
         


        
2条回答
  •  抹茶落季
    2021-01-26 13:05

    function mask(o, f) {
        setTimeout(function () {
            var v = f(o.value);
            if (v != o.value) {
                o.value = v;
            }
        }, 1);
    }
    
    function mphone(v) {
        var r = v.replace(/\D/g,"");
        r = r.replace(/^0/,"");
        if (r.length > 10) {
            // 11+ digits. Format as 5+4.
            r = r.replace(/^(\d\d)(\d{5})(\d{4}).*/,"(0XX$1) $2-$3");
        }
        else if (r.length > 5) {
            // 6..10 digits. Format as 4+4
            r = r.replace(/^(\d\d)(\d{4})(\d{0,4}).*/,"(0XX$1) $2-$3");
        }
        else if (r.length > 2) {
            // 3..5 digits. Add (0XX..)
            r = r.replace(/^(\d\d)(\d{0,5})/,"(0XX$1) $2");
        }
        else {
            // 0..2 digits. Just add (0XX
            r = r.replace(/^(\d*)/, "(0XX$1");
        }
        return r;
    }
    

    http://jsfiddle.net/BBeWN/

提交回复
热议问题