Auto Format Phone Number in Jquery
As far as I can work out, all you really need to do is this:
$('#ssn').keyup(function()
{
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
});
but this will only work when people enter digits, so I'd suggest an introducing an extra check:
$('#ssn').keyup(function(e) {
if ((e.keyCode > 47 && e.keyCode < 58) || (e.keyCode < 106 && e.keyCode > 95)) {
this.value = this.value.replace(/(\d{3})\-?/g, '$1-');
return true;
}
//remove all chars, except dash and digits
this.value = this.value.replace(/[^\-0-9]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="ssn">
A little more on the regex /(\d{3})\-?/g
:
This replaces group of 3 digits with itself, followed by a dash. The brackets create a back reference to the matched digits, that is used in the replacement string ($1-
-> $1 being the back reference).
Note that an optional dash is replaced, too, but not included in the back reference. if the input is 123
, and the replace pattern would be something like /(\d{3})/g
, or /(\d{3}\-?)/g
the value would become 123-4
, 123--45
, 123---456
and so on, doubling the dashes each time.
Warning:
This will give the user some grief, since the arrow keys and such won't work.Luckily, that's an easy fix: Just add the following code at the top of your function:
if (e.keyCode > 36 && e.keyCode < 41)
{
return true;
}
And the arrows work just fine. for other keys (such as delete, backspace, shift etc...) check this page.
For a full example: here's the fiddle
Since you're using jQuery you can try jquery masked-input-plugin.
There's a jsFiddle for you here where you can see how it works.
The source code for the project on GitHub can be found here.
The implementation is more than simple:
HTML:
<input id="ssn"/>
javascript:
$("#ssn").mask("999-999-999");
UPDATE:
Another good one can be found here.
For the formatting XXX-XXX-XXXX here is a simple solution:
if(this.value.trim().length <= 8){
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
}
Here is an example and you not need any framework or library or npm:
this.phone.addEventListener('keyup', event => {
if(this.phone.value.trim().length <= 8){
this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
}
}
You could also do this if you like:
this.phone.addEventListener('keyup', event => {
if(this.phone.value.trim().length <= 8){
this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
}else{
this.phone.value = this.phone.value.replace(/(\d{4})\-?/g,'$1');
}
}
Replace this this.phone
with your value.
I hope this helps.