Javascript phone mask for text field with regex

2020-05-06 13:37发布

问题:

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);" />

The problem is that I need to change this part of the code (OXX$1) for (0XX$1).

Current situation with 9 digit: (OXX99) 99999-9999.

Current situation with 8 digit: (OXX99) 9999-9999.

The correct formatting that I need with 9 digit: (0XX99) 99999-9999

The correct formatting that I need with 8 digit: (0XX99) 99999-9999

The amount of 8 or 9 digit is the choice of the user.

If I change the character 'O' for '0', causes an error in the mask.

Please, help!

回答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/



回答2:

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