I need to create a mask for a phone input with JavaScript only (I can not use jQuery). How can I do it?
I need to create a mask for a phone input with JavaScript only (I can not use jQuery). How can I do it?
Here's an example, it works with the 8 and 9 digits:
Script:
/* Máscaras ER */
function mascara(o,f){
v_obj=o
v_fun=f
setTimeout("execmascara()",1)
}
function execmascara(){
v_obj.value=v_fun(v_obj.value)
}
function mtel(v){
v=v.replace(/D/g,""); //Remove tudo o que não é dígito
v=v.replace(/^(d{2})(d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
v=v.replace(/(d)(d{4})$/,"$1-$2"); //Coloca hífen entre o quarto e o quinto dígitos
return v;
}
function id( el ){
return document.getElementById( el );
}
window.onload = function(){
id('telefone').onkeypress = function(){
mascara( this, mtel );
}
}
HTML:
<input type="text" name="telefone" id="telefone" maxlength="15" />
Source: link
Using this regex
^(\(11\) [9][0-9]{4}-[0-9]{4})|(\(1[2-9]\) [5-9][0-9]{3}-[0-9]{4})|(\([2-9][1-9]\) [5-9][0-9]{3}-[0-9]{4})$
This regex supports two phone formats
Phone format accepted: (99) 99999-9999 (this is compatible with the format currently used in São Paulo)
Another accepted format: (99) 9999-9999 (this is compatible with all other country formats)
For those who can use jQuery, the maskbrphone is used to mask eight- and nine-digit phones using or not DDD. The syntax is quite simple, eg:
$('#telefone').maskbrphone()
Use regular expression!
function mascararTel(v){
v=v.replace(/\D/g,"");
v=v.replace(/^(\d{2})(\d)/g,"($1) $2");
v=v.replace(/(\d)(\d{4})$/,"$1-$2");
return v;
}
<html>
<script>
function mask(e, id, mask){
var tecla=(window.event)?event.keyCode:e.which;
if((tecla>47 && tecla<58)){
mascara(id, mask);
return true;
}
else{
if (tecla==8 || tecla==0){
mascara(id, mask);
return true;
}
else return false;
}
}
function mascara(id, mask){
var i = id.value.length;
var carac = mask.substring(i, i+1);
var prox_char = mask.substring(i+1, i+2);
if(i == 0 && carac != '#'){
insereCaracter(id, carac);
if(prox_char != '#')insereCaracter(id, prox_char);
}
else if(carac != '#'){
insereCaracter(id, carac);
if(prox_char != '#')insereCaracter(id, prox_char);
}
function insereCaracter(id, char){
id.value += char;
}
}
<script>
<!--CODIGO HTML-->
<input onkeypress="return mask(event, this, '(##) ####-####')" maxlength="14" placeholder=" (DDD) 0000-0000">
</html>
As follows:
var value = "11912345678"
var formatted = value.replace(/^(\d{2})(\d{5})(\d{4}).*/,"($1) $2-$3");
alert(formatted);
This question has the answer here:
More specifically:
var input = document.getElementById( 'inputId' );
input.addEventListener( 'onchange', function() {
this.value = this.value.replace( /\(|\)|-/g, '' ).replace(/^(\d{3})(\d{3})(\d{4}).*/, '($1) $2-$3');
}, false );