我正在使用此功能来触摸屏幕并且几乎完美地工作。
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位数是用户的选择。
如果我将字符'O'更改为'0',则会导致掩码出错。
请帮忙!
答案 0 :(得分:5)
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;
}
答案 1 :(得分:-3)
我喜欢这个功能,我一直都在使用它。如果有人需要,我已经添加了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;
}