文本字段的Javascript电话面具与正则表达式 [英] Javascript phone mask for text field with regex
问题描述
我正在使用此功能来触摸屏幕并且几乎完美地工作。
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)
};
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;
}
这里我在文本字段中运行掩码:
Here I run the mask in the text field:
<input type="text" id="phone" name="phone" onkeypress="mask(this, mphone);" onblur="mask(this, mphone);" />
问题是我需要更改代码的这部分(OXX $ 1)适用于(0XX $ 1)。
The problem is that I need to change this part of the code (OXX$1) for (0XX$1).
9位数的当前情况:(OXX99)99999-9999 。
Current situation with 9 digit: (OXX99) 99999-9999.
8位数的当前情况:(OXX99)9999-9999 。
Current situation with 8 digit: (OXX99) 9999-9999.
我需要9位数的正确格式:(0XX99)99999-9999
The correct formatting that I need with 9 digit: (0XX99) 99999-9999
8位数我需要的格式正确:(0XX99)99999-9999
The correct formatting that I need with 8 digit: (0XX99) 99999-9999
8位或9位数是用户的选择。
The amount of 8 or 9 digit is the choice of the user.
如果我将字符O更改为0,则会导致掩码出错。
If I change the character 'O' for '0', causes an error in the mask.
请帮助!
推荐答案
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;
}
这篇关于文本字段的Javascript电话面具与正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!