Phone Mask Using jQuery Mask Plugin

Asked

Viewed 126,839 times

42

I need to change the "-" position on the mask.

<label for="telefone" >Telefone</label>
<input style="width:25%; margin-right:25% " type="tel" name="telefone" id="telefone" pattern="\([0-9]{2}\)[\s][0-9]{4}-[0-9]{4,5}" />
<script>$("#telefone").mask("(00) 0000-00009");</script>

With this solution the result is as follows for cell phones "(99) 1234-12345" and for fixed (99)1234-1234.

However I would like to leave to cell phones "(99) 12345-1234" and "(99)1234-1234".

  • Try to place an onblur event and count the characters, then if it is 9 digits change the mask

14 answers

49


You can do it like this:

jQuery("input.telefone")
        .mask("(99) 9999-9999?9")
        .focusout(function (event) {  
            var target, phone, element;  
            target = (event.currentTarget) ? event.currentTarget : event.srcElement;  
            phone = target.value.replace(/\D/g, '');
            element = $(target);  
            element.unmask();  
            if(phone.length > 10) {  
                element.mask("(99) 99999-999?9");  
            } else {  
                element.mask("(99) 9999-9999?9");  
            }  
        });
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
Telefone: <input type="text" class="telefone" />

  • Very good example and thank you! Utilizo Cdn oficial https://cdnjs.com/libraries/jquery.maskedinput

  • 3

    It is possible to make sure that if there is no "9" after the DDD, it is changed on time, and not only after clicking outside the input?

  • Excellent post @Thiago Thaison, helped me a lot.

  • thanks, very good

  • And in the case of both 2-digit DDD and 3-digit DDD, as it would be?

21

You can do it on Blur, I don’t see a better alternative. That is, do the following:

$('#fone').mask('(00) 0000-00009');
$('#fone').blur(function(event) {
   if($(this).val().length == 15){ // Celular com 9 dígitos + 2 dígitos DDD e 4 da máscara
      $('#fone').mask('(00) 00000-0009');
   } else {
      $('#fone').mask('(00) 0000-00009');
   }
});

I recently had a problem with using several inputs on the same screen, $('.phone-mask') because the mask was not updated, because the unmask keeps the selector in a variable, and how I should remask only the input then it didn’t work, which was my code:

$('.phone-mask').mask('(00) 0000-00009');
$('.phone-mask').blur(function(event) {
   if($(this).val().length == 15){ // Celular com 9 dígitos + 2 dígitos DDD e 4 da máscara
      $(this).mask('(00) 00000-0009');
   } else {
      $(this).mask('(00) 0000-00009');
   }
});

Did not work because the mask was not created with the selector this and yes with the selector .phone-mask, but if I reapplied the mask would apply to all screen inputs and I didn’t want that, then my code got like this:

$('.phone-mask').each(function(i, el){
   $('#'+el.id).mask("(00) 00000-0000");
})
function updateMask(event) {
    var $element = $('#'+this.id);
    $(this).off('blur');
    $element.unmask();
    if(this.value.replace(/\D/g, '').length > 10) {
        $element.mask("(00) 00000-0000");
    } else {
        $element.mask("(00) 0000-00009");
    }
    $(this).on('blur', updateMask);
}
$('.phone-mask').on('blur', updateMask);
  • Great tip! I will use this.

  • I modified to work cell phone sending. I changed the Pattern="([0-9]{2})[ s][0-9]{4,5}-[0-9]{4}".

  • 1

    I did with keyup and got show!

19

Another option to apply a mask on phones with 8 or 9 digits dynamically is to use the plugin jquery.inputmask.

Two masks are set one for eight digits and one for nine, the person responsible for keeping the hyphen in the right place (or moving it) is keepStatic:true(by default it is false) which makes the switch only when the new pattern is detected or is after typed the fourth character.

<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="view-source:https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $("#telefone").inputmask({
        mask: ["(99) 9999-9999", "(99) 99999-9999", ],
        keepStatic: true
      });
    });
  </script>
</head>

<body>
  <input type="text" id="telefone" name="telefone" />
</body>

</html>

11

You can do it like this:

var SPMaskBehavior = function (val) {
    return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
},
spOptions = {
    onKeyPress: function(val, e, field, options) {
        field.mask(SPMaskBehavior.apply({}, arguments), options);
    }
};

$('#telefone').mask(SPMaskBehavior, spOptions);

10

Much simpler my friends, follow my suggestion: I just needed this function:

1º - Set the default mask with the ninth digit option: (99) 9999-9999? 9

2º - Create an "onChange" event to modify the mask as soon as the field is changed (in this case, the phone).

Remembering that we are dealing with a mask regarding the plugin Masked Input Plugin. Many confuse with other plugins and so the code does not work. http://digitalbush.com/projects/masked-input-plugin

<script type="text/javascript">
jQuery( function($){
    $(".maskFone").mask("(99) 9999-9999?9");
    $(".maskFone").blur(function(event) {
        if($(this).val().length == 15){
          $('.maskFone').mask('(99) 99999-999?9');
        } else {
          $('.maskFone').mask('(99) 9999-9999?9');
        }
    });
});

9

Quasi-atomic solution:

    $(".phone-mask").mask("(99) 9999-9999?9").on("focusout", function () {
        var len = this.value.replace(/\D/g, '').length;
        $(this).mask(len > 10 ? "(99) 99999-999?9" : "(99) 9999-9999?9");
    });

9

I found a pure flame javascript Vanilla Masker and hard to find.

Between the code http://codepen.io/KingRider/pen/qNxror

or below

function inputHandler(masks, max, event) {
	var c = event.target;
	var v = c.value.replace(/\D/g, '');
	var m = c.value.length > max ? 1 : 0;
	VMasker(c).unMask();
	VMasker(c).maskPattern(masks[m]);
	c.value = VMasker.toPattern(v, masks[m]);
}

var telMask = ['(99) 9999-99999', '(99) 99999-9999'];
var tel = document.querySelector('input[attrname=telephone1]');
VMasker(tel).maskPattern(telMask[0]);
tel.addEventListener('input', inputHandler.bind(undefined, telMask, 14), false);

var docMask = ['999.999.999-999', '99.999.999/9999-99'];
var doc = document.querySelector('#doc');
VMasker(doc).maskPattern(docMask[0]);
doc.addEventListener('input', inputHandler.bind(undefined, docMask, 14), false);
div {
  font-family: Arial;
  padding: 5px;
  margin-bottom: 10px;
}  
input {
  box-sizing: border-box;
  padding: 10px;
  border-radius: 5px;
  border-color: black;
  width: 250px;
  font-size: 1.3em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-masker/1.1.0/vanilla-masker.min.js"></script>
<!-- Sandro Alvares (Não utilize jQuery & Javascript puro) -->
<div>
<label for="tel">Telefone</label>
<input attrname="telephone1" type="text">
<br><div>
<label for="doc">CPF/CNPJ</label>
<input id="doc" type="text">

Official Tutorial: https://github.com/BankFacil/vanilla-masker

He’s Brazilian, Vanilla is congratulations!

  • 2

    Very nice! I was almost giving up using mask without jquery.

8

According to the documentation:

var SPMaskBehavior = function (val) {
        return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
},
spOptions = {
    onKeyPress: function(val, e, field, options) {
                      field.mask(SPMaskBehavior.apply({}, arguments), options);
                    }
};

$('#id_tel_1').mask(SPMaskBehavior, spOptions);

I tested and worked perfectly.

4

  • 2

    Write a little more about your solution. Which plugin are you using? Where to find this inguinal? These answers help your answers get more complete and better viewed :D

4

can do using regular expressions. Ex:

function mascaraTelefone(number) {
    var regex = /^(.{1,2})(.{4,5})(.{4})/g;
    var number = `number`;
    var subst = `($1)$2-$3 `;

    var resultado = str.replace(regex, subst);
}

4

That was the one that solved my problem. Thank you very much!

jQuery("input.telefone")
        .mask("(99) 9999-9999?9")
        .focusout(function (event) {  
            var target, phone, element;  
            target = (event.currentTarget) ? event.currentTarget : event.srcElement;  
            phone = target.value.replace(/\D/g, '');
            element = $(target);  
            element.unmask();  
            if(phone.length > 10) {  
                element.mask("(99) 99999-999?9");  
            } else {  
                element.mask("(99) 9999-9999?9");  
            }  
        });
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
Telefone: <input type="text" class="telefone" />

3

I had problems with most of the current answers.. I was able to make it work with the following script:

    jQuery('input.your-tel')
        .mask('(99) 99999-9999')
        .focusout(function (event) {
            let target, phone, element;
            target = (event.currentTarget) ? 
                     event.currentTarget : 
                     event.srcElement;
            phone = target.value.replace(/\D/g, '');
            element = jQuery(target);
            element.unmask();
            if (phone.length > 10) {
                element.mask("(99) 99999-9999");
            } else {
                element.mask("(99) 9999-99999");
            }
        });

1

For version v1.14.12 of jquery mask plugin.

You can use the following solution: Where Z is the optional digit.

$(document).ready(function(){
    $('#telefone1').mask("+55 31 9999-9999Z", {
      translation: {
         'Z': {
            pattern: /[0-9]/, optional: true
         }
       }
    });

});

-1

This way you can add an optional digit.

$(function ($) { $("#telefone").mask("(99)9999-9999?9"); });
  • This way you will get the wrong mask with the 9 digit at the end: (99)9999-99999

Browser other questions tagged

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