29

I have a problem masking a phone input with jQuery and Masked Input Plugin.

There are 2 possible formats:

  1. (XX)XXXX-XXXX
  2. (XX)XXXXX-XXXX

Is there any way to mask it accepting both cases?

EDIT:

I tried:

$("#phone").mask("(99) 9999-9999"); 
$("#telf1").mask("(99) 9999*-9999");    
$("#telf1").mask("(99) 9999?-9999"); 

But it doesn't works as I would like.

The closest one was (xx)xxxx-xxxxx.

I would like to get (xx)xxxx-xxxx when I type the 10th number, and (xx)xxxxx-xxxx when I type the 11th. Is it posible?

HasanG
  • 12,734
  • 29
  • 100
  • 154
JHispa
  • 323
  • 1
  • 4
  • 6

15 Answers15

51

Try this - http://jsfiddle.net/dKRGE/3/

$("#phone").mask("(99) 9999?9-9999");

$("#phone").on("blur", function() {
    var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );

    if( last.length == 3 ) {
        var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
        var lastfour = move + last;
        var first = $(this).val().substr( 0, 9 );

        $(this).val( first + '-' + lastfour );
    }
});
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
24

Here is a jQuery phone number mask. No plugin required. Format can be adjusted to your needs.

Updated JSFiddle.

HTML

<form id="example-form" name="my-form">
    <input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>

JavaScript

$('#phone-number', '#example-form')

.keydown(function (e) {
    var key = e.which || e.charCode || e.keyCode || 0;
    $phone = $(this);

    // Don't let them remove the starting '('
    if ($phone.val().length === 1 && (key === 8 || key === 46)) {
        $phone.val('('); 
        return false;
    } 
    // Reset if they highlight and type over first char.
    else if ($phone.val().charAt(0) !== '(') {
        $phone.val('('+$phone.val()); 
    }

    // Auto-format- do not expose the mask as the user begins to type
    if (key !== 8 && key !== 9) {
        if ($phone.val().length === 4) {
            $phone.val($phone.val() + ')');
        }
        if ($phone.val().length === 5) {
            $phone.val($phone.val() + ' ');
        }           
        if ($phone.val().length === 9) {
            $phone.val($phone.val() + '-');
        }
    }

    // Allow numeric (and tab, backspace, delete) keys only
    return (key == 8 || 
            key == 9 ||
            key == 46 ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105)); 
})

.bind('focus click', function () {
    $phone = $(this);

    if ($phone.val().length === 0) {
        $phone.val('(');
    }
    else {
        var val = $phone.val();
        $phone.val('').val(val); // Ensure cursor remains at the end
    }
})

.blur(function () {
    $phone = $(this);

    if ($phone.val() === '(') {
        $phone.val('');
    }
});
Justin
  • 26,443
  • 16
  • 111
  • 128
  • This doesn't account for if the user backspaces all the way to the beginning of the input. It also doesn't allow the user to cmd+a or ctrl+a to select the whole thing (to delete or copy it) – Joshua Soileau Mar 29 '16 at 17:53
  • Updated code and fiddle so backspacing all the way is disallowed. – Justin Mar 29 '16 at 18:50
  • 1
    @Cooleshwar - It was just because the included version of jQuery was so old. I updated jQuery to v3.3.1 and it works fine in IE 11 now. – Justin Feb 19 '18 at 16:42
  • It works just fine. Much better than adding new dependency! – Nour Lababidi Jul 10 '18 at 13:33
4

Actually the correct answer is on http://jsfiddle.net/HDakN/

Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete

$("#phone").mask("(99) 9999-9999?9");


$("#phone").on("blur", function() {
    var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );

    if( last.length == 5 ) {
        var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );

        var lastfour = last.substr(1,4);

        var first = $(this).val().substr( 0, 9 );

        $(this).val( first + move + '-' + lastfour );
    }
});​
PH.
  • 377
  • 2
  • 9
4

You need a jQuery plugin for the mask works as well.

-- HTML --

<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">

-- JAVASCRIPT --

<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
    $("#phone").mask("(99) 9999-9999"); 
    $("#telf1").mask("(99) 9999*-9999");    
    $("#telf2").mask("(99) 9999?-9999"); 
});
</script>
Claudio Silva
  • 3,743
  • 1
  • 26
  • 27
  • Your code has a major vulnerability. Never add code directly from the latest branch. They could update anything and it would immediately show on your site. A versioned approach is better, https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/bb89c434e72030ce520764060f74b85b7ddce76e/dist/jquery.mask.min.js – Tim Apr 16 '22 at 14:52
  • They tell exactly the opposite. The latest always has the fixes of the last vulnerability. Now the big question : Who came before, the egg or the chicken? – Claudio Silva Apr 16 '22 at 15:20
  • No, you're not getting my point. It's not about fixing their bugs from a potential vulnerability, rather you are allowing code on your site that is directly from the author of the library w/o a version. If they release one malicious line of code, your site would be done. Also, if they have issues in their latest release your site could fail. This is why using versioned software is key. – Tim Apr 16 '22 at 15:23
3

You can use the phone alias with Inputmask v3

$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });

$(function() {
  $('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });
});
<label for="phone">Phone</label>
    <input name="phone" type="tel">

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask@3.3.7/dist/inputmask/inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask@3.3.7/dist/inputmask/inputmask.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask@3.3.7/dist/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask@3.3.7/dist/inputmask/inputmask.date.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask@3.3.7/dist/inputmask/inputmask.phone.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask@3.3.7/dist/inputmask/jquery.inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask@3.3.7/dist/inputmask/phone-codes/phone.js"></script>

https://github.com/RobinHerbots/Inputmask#aliases

HarlemSquirrel
  • 8,966
  • 5
  • 34
  • 34
  • I started to use this plugin. It works very good and it is up to date. Thanks for sharing it. – vhugo Nov 14 '19 at 16:34
2

Using jQuery Mask Plugin there is two possible ways to implement it:

1- Following Anatel's recomendations: https://gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9

2- Or without following Anatel's recomendations: https://gist.github.com/igorescobar/5327820

All examples above was coded using jQuery Mask Plugin and it can be downloaded at: http://igorescobar.github.io/jQuery-Mask-Plugin/

Igor Escobar
  • 1,047
  • 1
  • 12
  • 13
1
var $phone = $("#input_id");
var maskOptions = {onKeyPress: function(phone) {
    var masks = ['(00) 0000-0000', '(00) 00000-0000'];
    mask = phone.match(/^\([0-9]{2}\) 9/g)
        ? masks[1]
        : masks[0];
    $phone.mask(mask, this);
}};
$phone.mask('(00) 0000-0000', maskOptions);
NovoK
  • 146
  • 5
1

With jquery.mask.js

http://jsfiddle.net/brynner/f9kd0aes/

HTML

<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">

JS

// Function
function phoneMask(e){
    var s=e.val();
    var s=s.replace(/[_\W]+/g,'');
    var n=s.length;
    if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
    $(e).mask(m);
}

// Type
$('body').on('keyup','.phone',function(){   
    phoneMask($(this));
});

// On load
$('.phone').keyup();

Only jQuery

http://jsfiddle.net/brynner/6vbrqe6z/

HTML

<p class="phone">85999998888</p>
<p class="phone">8599998888</p>

jQuery

$('.phone').text(function(i, text) {
    var n = (text.length)-6;
    if(n==4){var p=n;}else{var p=5;}
    var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
    var text = text.replace(regex, "($1) $2-$3");
    return text;
});
Brynner Ferreira
  • 1,527
  • 1
  • 21
  • 21
0

The best way to do this is using the change event like this:

$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {

    var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );

    if( last.length == 3 ) {
        var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
        var lastfour = move + last;
        var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999

        $(this).val( first + '-' + lastfour );
    }
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
leoalmar
  • 226
  • 5
  • 14
0

The best way to do it on blur is:

                        function formatPhone(obj) {
                        if (obj.value != "")
                        { 
                            var numbers = obj.value.replace(/\D/g, ''),
                            char = {0:'(',3:') ',6:' - '};
                            obj.value = '';
                            upto = numbers.length; 

                            if(numbers.length < 10) 
                            { 
                                upto = numbers.length; 
                            }
                            else
                            { 
                                upto = 10; 
                            }
                            for (var i = 0; i < upto; i++) {
                                obj.value += (char[i]||'') + numbers[i];
                            }
                        } 
                    }
0

As alternative

    function FormatPhone(tt,e){
  //console.log(e.which);
  var t = $(tt);
  var v1 = t.val();
  var k = e.which;
  if(k!=8 && v1.length===18){
    e.preventDefault();
  }
  var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
  if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
 e.preventDefault();
  }
  else{
    setTimeout(function(){
      var v = t.val();
      var l = v.length;
      //console.log(l);
      if(k!=8){
        if(l<4){
          t.val('+7 ');
        }
        else if(l===4){
          if(isNaN(q)){
            t.val('+7 (');
          }
          else{
            t.val('+7 ('+q);
          }
        }
        else if(l===7){
          t.val(v+')');
        }
        else if(l===9){
          t.val(v1+' '+q);
        }
        else if(l===13||l===16){
          t.val(v1+'-'+q);
        }
        else if(l>18){
          v=v.substr(0,18);
          t.val(v);
        }
        }
        else{
          if(l<4){
            t.val('+7 ');
          }
        }
    },100);
  }
}
Choo Hwan
  • 416
  • 3
  • 12
0

I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number

Simple Add jquery-input-mask-phone-number plugin in to your HTML file and call usPhoneFormat method.

$(document).ready(function () {
    $('#yourphone').usPhoneFormat({
        format: '(xxx) xxx-xxxx',
    });   
});

Working JSFiddle Link https://jsfiddle.net/1kbat1nb/

NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number

GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number

Raja Rama Mohan Thavalam
  • 8,131
  • 2
  • 31
  • 30
0

If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.

The cleanest way:

var options =  {
    onKeyPress: function(phone, e, field, options) {
        var masks = ['(00) 0000-00000', '(00) 00000-0000'];
        var mask = (phone.length>14) ? masks[1] : masks[0];
        $('.phone-input').mask(mask, options);
    }
};

$('.phone-input').mask('(00) 0000-00000', options);
Artur Haddad
  • 1,429
  • 2
  • 16
  • 33
0

Yes use this

$("#phone").inputmask({"mask": "(99) 9999 - 9999"});

Link here

Sumit Kumar Gupta
  • 2,132
  • 1
  • 22
  • 21
0
$('.phone').focus(function(e) {
    // add mask
    $('.phone')
        .mask("(99) 99999999?9")
        .focusin(function(event)
        {
            $(this).unmask();
            $(this).mask("(99) 99999999?9");
        })
        .focusout(function(event)
        {
            var phone, element;
            element = $(this);
            phone = element.val().replace(/\D/g, '');
            element.unmask();

            if (phone.length > 10) {
                element.mask("(99) 99999-999?9");
            } else {
                element.mask("(99) 9999-9999?9");
            }
        }
    );
});