29

My CodePen: http://codepen.io/leongaban/pen/cyaAL

I have an input field for a phone number which allows up to 20 characters (for international numbers).

I'm also using the Masked input jQuery plugin by Josh Bush to format the phone number in the input to make it 'pretty'.

enter image description here

  • My problem is that in the requirements when the phone is 10 digits or less, it should use the Masked input formatting.

  • However when the phone number is longer then 10 digits, the formatting should be removed.



Here is my current: CodePen, Cell Phone is the input field where I'm trying to accomplish this. Work Phone is an example of the default functionality of the Mask input plugin.

How would you go about this problem?

jQuery for Cell Phone input field:

case '2':
    console.log('created phone input');
    $('.new_option').append(myphone);
    $('.added_mobilephone').mask('(999) 999-9999? 9');
    $('.added_mobilephone').keypress(function(event){

      if (this.value.trim().length > 10) {
        console.log('this.value = '+this.value.trim());
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }

      /*if (this.value.length < 9) {
        console.log(this.value);
        console.log('less then 10');
        $('.added_mobilephone').mask('(999) 999-9999? 9999999999');
      } else if (this.value.length > 9) {
        console.log(this.value);
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }*/
    });
    break;
4
  • 2
    Have you checked out this question yet? stackoverflow.com/questions/2580550/… That question's method of checking a box indicating international # or not could be good from a user-experience standpoint as well (in your current version, int'l users may get confused when initially presented with the default US phone format) Commented Jul 31, 2013 at 20:44
  • Oh sweet thanks for the link! Checking it out now, will see if I can get it to work better
    – Leon Gaban
    Commented Jul 31, 2013 at 20:50
  • 1
    Thank you. I was able to get this plugin working for my form input :)
    – Andy
    Commented May 3, 2018 at 19:11
  • $("#pr_phone").inputmask("+9 999 999 9999", { onKeyValidation: function (key, result) { } }); I have added it like this example. But i want to set '+1' fixed for country code so that no one can change it. Please suggest. Thanks.
    – Kamlesh
    Commented Apr 19, 2020 at 16:14

10 Answers 10

45
$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1)$2-$3"));
});

This will work for sure and will properly handle populating the full string at once (e.g., 1234567890).

/* example jquery use */

$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1)$2-$3"));
});
/* use your css to beautify the form */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- form input for example user -->
<form>
  <input type="text" name="phone" placeholder="Phone Number" />
</form>

1
  • 3
    I wish I could upvote this 100 times. Best solution. Commented Sep 15, 2016 at 15:00
36

You've probably already solved this problem, but it's worth noting for future reference that anyone else with the need to apply multiple masks to a control may want to explore this inputmask plugin.

It has more callbacks, settings and many out of the box mask types(be sure to take a look at the extension files). You can also define multiple masks for a control, and the plugin will try and apply the appropriate mask based on the value.

Here is a fiddle to demo the previous statement:

$(window).load(function()
{
   var phones = [{ "mask": "(###) ###-####"}, { "mask": "(###) ###-##############"}];
    $('#textbox').inputmask({ 
        mask: phones, 
        greedy: false, 
        definitions: { '#': { validator: "[0-9]", cardinality: 1}} });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
<input type='text' id='textbox' />

5
  • do I have to add the whole paste you shared through jsfiddle ? Commented Jun 11, 2015 at 5:30
  • 1
    @KhanShahrukh That's one way of doing it. I just updated the answer with a snippet that includes a CDN for inputmask. You should have everything you need in that bundle.
    – Kevin
    Commented Jun 11, 2015 at 18:57
  • I'm aware of the outdatedness of this answer. @Roop Kumar has given a much better answer below. Commented Sep 15, 2016 at 15:01
  • The OP asked how to do this in a very specific library. The library I recommended is a branch of what he's using. If all you need to do is simply format text then RoopKumars answer is better suited. The plugin being used is heavier, but does much more than format text. It's pretty great, one of my favorites. I'd still recommend it if you're able to use it.
    – Kevin
    Commented Mar 2, 2017 at 0:20
  • $("#pr_phone").inputmask("+9 999 999 9999", { onKeyValidation: function (key, result) { } }); I have added it like this example. But i want to set '+1' fixed for country code so that no one can change it. Please suggest. Thanks.
    – Kamlesh
    Commented Apr 19, 2020 at 16:14
25

This was very helpful, I only add some code to make it works when user delete some characters, I gave the option of entering only numbers and a max length. This works for me :)

$(document).ready(function(){
  /***phone number format***/
  $(".phone-format").keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
      return false;
    }
    var curchr = this.value.length;
    var curval = $(this).val();
    if (curchr == 3 && curval.indexOf("(") <= -1) {
      $(this).val("(" + curval + ")" + "-");
    } else if (curchr == 4 && curval.indexOf("(") > -1) {
      $(this).val(curval + ")-");
    } else if (curchr == 5 && curval.indexOf(")") > -1) {
      $(this).val(curval + "-");
    } else if (curchr == 9) {
      $(this).val(curval + "-");
      $(this).attr('maxlength', '14');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="phone-format"  type="text" placeholder="Phone Number">

9
  • 3
    This should be the best answer.
    – Rivers
    Commented Dec 17, 2015 at 17:22
  • Bundle of Thanks. Rivers
    – Atif Tariq
    Commented Dec 17, 2015 at 17:26
  • 6
    This does not work well when trying to erase what you have written!
    – Feek
    Commented Jan 7, 2016 at 5:50
  • @Leti Thank you very much.
    – Atif Tariq
    Commented May 5, 2017 at 15:03
  • @BernieCarpio Thank you very much
    – Atif Tariq
    Commented Sep 5, 2018 at 11:25
9

In your case

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>

<input type="text" class="form-control" data-mask="(999) 999-9999">

with jasny bootstrap plugin

2
  • ah! made my life a tiny bit easy. worked like a charm Commented Nov 12, 2023 at 15:35
  • Working Fine, Thank Your Commented Jul 8 at 5:17
4

I tried some of the non-plugin answers but they unfortunately had undesirable side effects when editing the phone number. Here is a solution that I ended up creating that is simple and has no special external 3rd party lib dependency:

  • Does not require any plugins --> just JS and JQuery
  • Filters out non-digits (i.e. noise) automatically
  • Shifts left the phone number digits on deletion of digits
  • Maintains format / does not break down on deletion
  • Does nothing if nothing changes e.g. allows cursor to move left/right to make change vs. other solutions which kept cursor pegged to end

CAVEAT: The phone number considered is only North America which was fine in my case as this was used for local community soccer registration in Canada.

$("input[name='phone_num']").keyup(function() {
  var val_old = $(this).val();
  var val = val_old.replace(/\D/g, '');
  var len = val.length;
  if (len >= 1)
    val = '(' + val.substring(0);
  if (len >= 3)
    val = val.substring(0, 4) + ') ' + val.substring(4);
  if (len >= 6)
    val = val.substring(0, 9) + '-' + val.substring(9);
  if (val != val_old)
    $(this).focus().val('').val(val);
});
1
  • I wish I could upvote this 1,000 times. Thanks @nikolaosinlight this is flawless. Commented Aug 9, 2019 at 16:54
4

Input type text to input type telephone number. max-length, placeholder using jquery.

// Used to format phone number and add placeholder and max-length
function phoneFormatter() {
 $(' input[type="text"]').attr({ placeholder : '(___) ___-____' });
  $('input[tabindex="111"]').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
     
    }
    $(this).val(number)
    $('input[type="text"]').attr({ maxLength : 10 });
    
  });
};

$(phoneFormatter);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input_111[]" value="" tabindex="111">

2
  • Above jQuery Easily maintain in page Commented Aug 26, 2017 at 9:50
  • Perfect! this is it, what I was looking for. 👍 Commented Feb 10, 2022 at 9:31
2

Check the below answer out.

I created for the TSP code(One of my project) but the similar structure works for the Phone number. Solution is fairly simple.
I am using the KeyCode to the below solution. More information about the keycode could be found here.

 $(function () {
    $('#txtphonenumber').keydown(function (e) {
    var key = e.charCode || e.keyCode || 0;
    $text = $(this); 
       if (key !== 8 && key !== 9) {
          if ($text.val().length === 3) {
             $text.val($text.val() + '-');
          }
          if ($text.val().length === 7) {
             $text.val($text.val() + '-');
          }
       }
       return ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || key == 46 || key == 8 || key == 9 );
      // KeyCode from 48 to 57 are the Numeric characters
      // KeyCode from 96 to 105 are the numpad 0 to numpad 9
      // KeyCode delete 46
      // KeyCode backspace 8
      // KeyCode tab 9
  })
});
2

Here is my solution (for US numbers) that works as you type

const maskPhoneNumber = (s) => {
  let o = '';
  o += s.length >= 3 ? `(${s.substring(0, 3)}` : s;
  o += s.length >= 4 ? `) ${s.substring(3, 6)}` : s.substring(3);
  o += s.length >= 7 ? `-${s.substring(6)}` : '';
  return o;
};
0

Similar solution above but in this script the format is applying meanwhile the user is typing. Adding mask in the phone number - Brazilian Phone Format (00) ?0000-0000. It can be helpful for others as well.

    //Add mask (00) ?0000-0000 in the phone number - Brazil Format
    $('#iTel').on("keyup blur", function(e){
    	var v = $(this).val();
    	v = v.replace(/[^\d]/g,'');
    	if(v.length < 6){
    		v = v.replace(/(\d{2})/, '($1) ');
    	}else if(v.length < 10){
    		v = v.replace(/(\d{2})(\d{4})/, '($1) $2-');
    	}else if(v.length < 11){
    		v = v.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');				
    	}else {
    		v = v.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
    	}
    $(this).val(v);		
       });
    <!DOCTYPE html>
     <html lang="en">
     <head>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
    <form method="post" id="cadForm" action="incluir.php">
    <div class="form-row">
     <div class="form-group col-md-12">
    	<label for="iTel" class="col-form-label">Phone</label>
    	<div class="input-group">
    	<span class="input-group-addon"><i class="fa fa-phone" aria-hidden="true"></i></span>
    	<input type="text" class="form-control" name="iTel" id="iTel" maxlength="15" placeholder="(xx) ?xxxx-xxxx..." pattern="[(][0-9]{2}[)][\s][0-9]{4,5}[-][0-9]{4}$" title="Please, type only number: (00) ?0000-0000">
    	</div>			
    </div>
      </body>
     </html>

0

extension to Roop Kumar answer if one only wants to keep digits

than add replace(/\D/g,'')

$(this).val($(this).val().replace(/\D/g,'').replace(/^(\d{3})(\d{3})(\d+)$/, "($1)$2-$3"));

Hopes that helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.