3

I am trying to write a regex for US phone numbers where user can enter the number and dash comes automatically. But here the drawback is if user enters "123" and then "-" the regex breaks and instead of 123-456-7890 it becomes 123-4567890 Here is the regex code:

  $('#AccountFrm_telephone').attr('maxlength', '12');

$('#AccountFrm_telephone').keyup(function(){
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "$1-$2-$3"));
});

Maybe There is something that we add in regex so that user can not type dash?

Ron
  • 55
  • 6
  • this part `(\d)+` should be `(\d+)` – Nullman Feb 23 '17 at 17:05
  • @Nullman No thats not working :( – Ron Feb 23 '17 at 17:08
  • i ave put your string into `var x` and the following worked fine `x.replace(/^(\d{3})(\d{3})(\d+)$/, "$1-$2-$3")` – Nullman Feb 23 '17 at 17:10
  • I tried it but it takes dash "-" after 3 number if user enters "-" then breaks the regex still – Ron Feb 23 '17 at 17:13
  • ah, then like the removed post suggested, use this: `/^(\d{3})-?(\d{3})-?(\d+)$/, "$1-$2-$3"` the `?` notes 0 or 1 times – Nullman Feb 23 '17 at 17:14
  • Yup this works thanks @Nullman – Ron Feb 23 '17 at 17:18
  • Doesn't a onkey up handler return on _each_ key up ? If so, you won't get a complete phone number, so using `^(\d{3})-?(\d{3})-?(\d+)$/` will never match. I wouldn't do it this way. I'd use a regex to strip it down to 1-10 numbers. Then use a string function to _insert_ a dash - at the right places if the string is long enough. –  Feb 23 '17 at 17:44
  • `Maybe There is something that we add in regex so that user can not type dash` - If this _is_ an onkeyup type handler, you should be able to write over whatever key character is shown. –  Feb 23 '17 at 17:49

3 Answers3

1

Maybe try the following:

$('#AccountFrm_telephone').attr('maxlength', '12');

$('#AccountFrm_telephone').keyup(function(){
    $(this).val($(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3"));
});
Chris Cruz
  • 1,829
  • 13
  • 15
1

for completes: you have 2 issues first this part (\d)+ should be (\d+) or you wont capture the last group on numbers correctly. the second part is that you aren't handling possible dashes in the input, so try something like:

.replace(/^(\d{3})-?(\d{3})-?(\d+)$/, "$1-$2-$3")

the question marks (?) denote 0 or 1 times, meaning the user can input the dashes if he wants

Nullman
  • 4,179
  • 2
  • 14
  • 30
1

Try this:

$("#input1").on('keyup', e => {
    e.target.value = e.target.value.replace(/(\d{3})-?(\d{3})-?(\d+)/, '$1-$2-$3')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
Maciej Kozieja
  • 1,812
  • 1
  • 13
  • 32