5

I have textfield to let user to fill his phone number, but I need to force that user to fill it in certain format like this: (0599)-9-111222.

my code is:

function fomratPhone(phone){
     for(var i = 0; i < phone.length; i++){
         if (phone[0] == "(") continue;
         else return false; 

         if (phone[5] == ")") continue;
         else return false;   

         if (phone[6] == "-" || phone[8] == "-") continue;
         else return false; 
     }
     return true; 
}

but this code does not work.

Ayman Hussein
  • 3,817
  • 7
  • 28
  • 48
  • 1
    It will probably be easier to strip all non-numeric characters and check if the phone number is the correct length – cfs Jun 13 '13 at 12:18
  • 1
    @AymanHussein do a regex and validate if the thing match – fGo Jun 13 '13 at 12:20
  • I need placehoder in textfield to help user and onkeypress the user should fill the digits and the other chars should be printed. – Ayman Hussein Jun 13 '13 at 12:21
  • @AymanHussein—Not a good idea. As soon as the user starts typing, the placeholder disappears so they can no longer see the required format. Placeholders are not a replacement for onscreen hints. – RobG Jun 13 '13 at 12:23
  • Just I am thinking out loud. So, what is the good idea for do that? – Ayman Hussein Jun 13 '13 at 12:25
  • 2
    try this https://github.com/RobinHerbots/jquery.inputmask – sangram parmar Jun 13 '13 at 12:26
  • Instead of a placeholder I suggest to use an always-visible on screen hint. It can be a label or you can use any kind of hint system (there are many fance javascript libraries out there). Also you should expand your question because it is not so clear what are you trying to achieve. – ragklaat Jun 13 '13 at 12:27
  • Thanks alot sangram parmar that what i want Input mask js library :) – Ayman Hussein Jun 13 '13 at 12:30

6 Answers6

6

Another alternative is the jQuery inputmask plugin

<input type="text" name="phone" id="phone" />

<!-- include jQuery & inputmask plugin -->
<script type="text/javascript">
    $(function(){
        $("#phone").inputmask("mask", {"mask": "(9999)-9-999999"});
    });
</script>

This is just another variation of what NF supplied. I haven't used the one NF mentioned, but I have used this one with no problems. Also, because it's a github project, should you find errors or make corrections you can fork the project and create a pull request with any new additions.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • I liked using InputMask's HTML attribute system more: `$(document).ready(function () { Inputmask().mask(document.querySelectorAll("input")); });` Within the HTML input tags add this attribute: `data-inputmask="'mask': '(999) 999-9999'"` – Eric Milliot-Martinez Mar 16 '18 at 14:54
2

You can use this jQuery masked input plugin

N F
  • 31
  • 2
1

You could use the Text Mask library. They have a nice demo here.

To force the text field into a phone number, you could so something like this (taken from here):

<script
  type="text/javascript"
  src="./node_modules/vanilla-text-mask/dist/vanillaTextMask.js"></script>
<script type="text/javascript">
  var phoneMask = ['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]

  // Assuming you have an input element in your HTML with the class .myInput
  var myInput = document.querySelector('.myInput')

  var maskedInputController = vanillaTextMask.maskInput({
    inputElement: myInput,
    mask: phoneMask
  })

  // Calling `vanillaTextMask.maskInput` adds event listeners to the input element. 
  // If you need to remove those event listeners, you can call
  maskedInputController.destroy()
</script>

They also have wrappers for Angular, React, and others.

Chris Smith
  • 2,928
  • 4
  • 27
  • 59
0

assuming that the entered numbers must be at the mentioned length each. Else just strip the {amount} pairs

function fomratPhone(phone){
     return phone.length == 15 && /^\((\d){4}\)-[\d]-(\d){6}$/g.test(phone);
}
Alex
  • 9,911
  • 5
  • 33
  • 52
0

In case it's handy to someone else: Here is a way to make it format as you type. It's adapted from this post.

function phone(n){
    var x = n.replace(/\D/g, '').match(/(\d{0,4})(\d{0,1})(\d{0,6})/);
    return (!x[2] ? x[1] : '(' + x[1] + ')' + x[2] + (x[3] ? '-' + x[3] : ''));
}

Calling phone('39020343993') gives you "(3902)0-343993". Calling phone('3902034') gives you "(3902)0-34".

Community
  • 1
  • 1
PeterM
  • 439
  • 2
  • 9
-1

Dunno why cfs delete his/her answer, it's fine. You can simply delete any non-numeric character, check that there are 11 digits, then reformat the digits to your required format, e.g.

var n = '1234 5 678901'
n = n.replace(/\D/g,'');

// do validation tests
if (n.length == 11) {

    // If passed tests, reformat as required
    console.log(n.replace(/(\d{4})(\d)(\d{6})/,'($1)-$2-$3')); // (1234)-5-678901
} 
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I do not need to strip chars, what iI need format mask. thank you for your answer :) – Ayman Hussein Jun 13 '13 at 12:42
  • Making users enter a complicated pattern to fit your requirements is just making life difficult for them. And a regular expression (e.g. Alex's answer) will do the job just as well as a format mask and you aren't reliant on someone else's code. – RobG Jun 13 '13 at 20:15