JavaScript的电话面膜用正则表达式文本字段(Javascript phone mask fo

2019-08-19 09:11发布

我使用这个功能,手机屏蔽和近乎完美的作品。

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

function execmask() 
{ 
    v_obj.value = v_fun(v_obj.value) 
};

function mphone(v){
    v=v.replace(/\D/g,"");           
    v=v.substring(0, 11);
    v=v.replace(/^(\d{2})(\d)/g,"(OXX$1) $2"); 
    v=v.replace(/(\d)(\d{4})$/,"$1-$2"); 
    return v;
}

在这里,我跑在文本字段面膜:

<input type="text" id="phone" name="phone" onkeypress="mask(this, mphone);" onblur="mask(this, mphone);" />

问题是,我需要为(0XX $ 1)修改代码(OXX $ 1)的这一部分。

目前的情况与9位:(OXX99)99999-9999。

目前的情况与8位:(OXX99)9999-9999。

正确的格式,我需要用9位:(0XX99)99999-9999

正确的格式,我需要用8位:(0XX99)99999-9999

8或9位的量为所述用户的选择。

如果我改变为“0”字“O”,导致掩模中的错误。

请帮忙!

Answer 1:

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/



Answer 2:

我喜欢这个功能,我用它所有的时间。 如果有人需要他们,我已经添加了其他2个口罩。 据我所知,他们没有直接回答这个问题,但他们是超级有用。

//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;
}


文章来源: Javascript phone mask for text field with regex