How to make a Javascript mask for type tel?

Asked

Viewed 839 times

2

Guys, I created a form and a field for the user to fill in your phone. That is: type="tel". What I want is a Javascript code that, when the user enters the phone, the code automatically transforms the phone to this format (xx) xxxx-xxxx. In short: I want the code to automatically fill in the parentheses, the space and the hyphen, leaving the phone like this:

(xx) xxxx-xxxx

Obs: respecting parentheses, space and hyphen.

Another question: you can do this with HTML itself?

If you can, post the HTML part where I call the method, because I haven’t studied Javascript yet. Thank you.

2 answers

2

I found this Code and it’s working. See if it fits 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 Telefone

1

Yes, you can do it directly in HTML5 via 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 the values that match this pattern. If you want to validate cell phone numbers you change the first one [0-9]{4} for [0-9]{5} or else to [0-9]{4,5} if you want to validate both.

  • What do these two mean "" ?

  • 1

    Keep in mind that the question speaks in mask specifically and not validation.

  • 2

    Martha, in regular expression parentheses are used in syntax, "(" is to be interpreted as a common character.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.