Javascript phone mask for text field with regex

前端 未结 2 619
北荒
北荒 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: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;
    }
    

提交回复
热议问题