How to make a JavaScript mask for the type tel?

2

Well, I've created a form and a field for the user to fill in the phone. That is: field type="tel". What I want is a JavaScript code that, when the user inserts the phone, the code will automatically transform the phone to this format (xx) xxxx-xxxx. In short, I want the code to automatically populate the parentheses, space, and hifen, leaving the phone like this:

(xx) xxxx-xxxx

Note: respecting the parentheses, the space and the hyphen.

Another question: can you do this with HTML itself?

If you can, post the part of the HTML in which I call the method, as I have not studied JavaScript yet. Thank you.

    
asked by anonymous 28.04.2018 / 13:02

2 answers

2

I found this code and it works. See if it suits you.

<html>
<head>
    <title>Mascara Telefone</title>
<script type="text/javascript">
/* 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 );
    }
}
</script>

</head>
<body>

    <input type="text" name="telefone" id="telefone" maxlength="15" />

</body>
</html>

Source: Mascara Phone

    
28.04.2018 / 13:43
1

Yes, you can do it directly in HTML5 through the parameter pattern and using a regular expression:

<input type="text" id="tel" pattern="\([0-9]{2}\) [0-9]{4}-[0-9]{4}">

In this case the browser will consider valid values that match this pattern. If you want to validate cell phone numbers you should change the first [0-9]{4} to [0-9]{5} or else to [0-9]{4,5} if you want to validate both.

    
28.04.2018 / 13:35