Javascript phone mask for text field with regex

前端 未结 2 615
北荒
北荒 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/

    0 讨论(0)
  • 2021-01-26 13:14

    I love this function and I use it all the time. I've added 2 other masks if anyone needs them. I understand that they don't directly answer the question, but they are super useful.

    //Social Security Number for USA
     function mssn(v) {
        var r = v.replace(/\D/g,"");
        r = r.replace(/^0/,"");
        if (r.length > 9) {
            r = r.replace(/^(\d\d\d)(\d{2})(\d{0,4}).*/,"$1-$2-$3");
            return r;
        }
        else if (r.length > 4) {
            r = r.replace(/^(\d\d\d)(\d{2})(\d{0,4}).*/,"$1-$2-$3");
        }
        else if (r.length > 2) {
            r = r.replace(/^(\d\d\d)(\d{0,3})/,"$1-$2");
        }
        else {
            r = r.replace(/^(\d*)/, "$1");
        }
        return r;
    }
    
    //USA date
    function mdate(v) {
       var r = v.replace(/\D/g,"");
       if (r.length > 4) {
        r = r.replace(/^(\d\d)(\d{2})(\d{0,4}).*/,"$1/$2/$3");
       }
       else if (r.length > 2) {
        r = r.replace(/^(\d\d)(\d{0,2})/,"$1/$2");
       }
       else if (r.length > 0){
             if (r > 12) {
               r = "";
             }
       }
       return r;
    }
    
    0 讨论(0)
提交回复
热议问题