Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

formatting phone numbers 1

Status
Not open for further replies.

TheConeHead

Programmer
Joined
Aug 14, 2002
Messages
2,106
Location
US
Any suggestions for having phone numbers formatyted the same (ie (xxx) xxx-xxxx) with extensions being a possibility - I'd rather to a jscript or server-side solution as opposed to having sepearte form elements....

[conehead]
 
I'd use a regular expression. Do you want to force them to type it in the way you posted above (xxx) xxx-xxxx or allow them to type it in different ways and apply the formatting in case they don't supply it?

-kaht

[small] <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
[banghead] [small](He's back)[/small]
 
You could get fancy and trap the keypresses in the field testing the value every keypress and automatically adding in the parens and hyphen as you go.
It can get somewhat complex though especially trying to account for someone pasting data into the field.

You could as kaht suggested use regular expressions to test the value. If you want to force into a specific format then onchange you read the value, strip all non-numerical characters, validate the number is enough digits then insert your parens and hypen into the proper positions and write it back out to the field.
Using this method you do not have to test for every possible variation in what they entered, you just modify it to fit your own schema.


Stamp out, eliminate and abolish redundancy!
 
I'd rather let them type it anyway they want and then format it - but then I need to account for the various wa
ys they could type it (maybe include area code - maybe not) How would I go about that?

[conehead]
 
You could do as others suggest and trap onkeyup... then display the formatted phone number in a <span> or something. This way people could see how it was going to be formatted as they typed it (and you could handle ctrl-v pasting etc as well). Maybe provide them with an option to format the phone number (on by default) and based on the preview of their phone number they can decide wether or not to use the formatting you propose (ideal for odd phone number lengths etc).

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
The problem with onkeyup at least in IE is that the return value for the keypress is ALWAYS the uppercase value. You can use onkeypress to get the true value but (at least in IE) it does not trigger CTRL events when inside an input field. I fought with this for a long time and came up with something that works (at least in IE) but it does not yet account for right click paste or pasting from the edit menu.
*Sigh*

ANYWAY.
TheConeHead, as I suggested above, when the onchange event is triggered read the value from the field, strip all non-numeric characters and check the length of what remains. If you end up with 7 digits you know the number is either invalid or they did not enter an areacode and you can either reject it or insert a hyphen at position 4.
If it is 10 digits then you can add the parens and hyphen and write the string back to the field all formatted.
The only thing you have to be concerned with is if they entered enough digits to meet your requirements.
You could even test to see if the first digit is a 1 and strip it because (I do not believe) any area codes or local exchanges ever begin with a 1 and if they entered one at the beginning of the string they might have been doing it like 1-555-555-5555.


Stamp out, eliminate and abolish redundancy!
 
Ahh, here are some other phone numbers:

UK mobile number: +447957123456 (this is faked)
NZ landline number: +6432123456 (this is faked)
AUS landline number: +61393123456 (this is faked)

They all share 2 digit country codes (the US and Canada share the same country code of "1" as well). But the important thing is that they are all different lengths.

If you are coding a solution that is for US and Canada domestic phone numbers only... then fine. If not... consider that other countries have different length phone numbers and may need to include the country code.

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Country is not an issue, but I need to account for

(xxx) xxx-xxxx

xxx-xxxx xt.xx

xxx xxx-xxxx ext:xxxx

xxx-xxxx xxx

and any varioation thereof - I need them to all be formatted the same....

[conehead]
 
yeah - seems like more form elements is the best way...

[conehead]
 
you tempted me. here's my quick solution:

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Untitled</title>
	
	<script type="text/javascript"><!--
	
	function doFilter(o) {
		var p = o.value;
		p = p.replace(/[^0-9]/g, "");
		
		if ( p.length >= 6 )
			o.value = "(" + p.substr(0, 3) + ") " + p.substr(3, 3) + "-" + p.substr(6, 4);
		else if ( p.length >= 3 )
			o.value = "(" + p.substr(0, 3) + ") " + p.substr(3, 3);
	}
	
	//--></script>
</head>

<body>

<form>
	<input type="text" onkeyup="doFilter(this);" />
</form>

</body>
</html>



*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
[banghead]
 
(with country code):

Code:
function doFilter(o) {
    var p = o.value;
    p = p.replace(/[^0-9]/g, "");

    if ( p.length >= 7 )
        o.value = p.substr( 0, 1 ) + " (" + p.substr(1, 3) + ") " + p.substr(4, 3) + "-" + p.substr(7, 4);
    else if ( p.length >= 4 )
        o.value = p.substr( 0, 1 ) + " (" + p.substr(1, 3) + ") " + p.substr(4, 3);
    else if ( p.length == 1 )
        o.value = p.substr( 0, 1 ) + " (";
}



*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
[banghead]
 
cLFlaVA, that's pretty slick.
The one major issue is that the client cannot easily backspace to make changes.
Or more accurately you can backspace until you hit a non-numeric character and the function overwrites your field.
If you hold the backspace key down the auto-repeat can occur faster than the function can respond and you can get past the non-numeric but you end up going ALL the way back by the time you release the key.

It would be nice to test for a 1 as the first number and trim that out as well providing it is a Canadian or U.S. phone number since some people are likely to type 1-xxx-xxx-xxxx for the number.

But it is a slick piece of code nonetheless.

Stamp out, eliminate and abolish redundancy!
 
theniteowl,

this takes care of the backspace issue. the test for the first number was accounted for in my 2nd code post. it's integrated here.

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>
    
    <script type="text/javascript"><!--
    
function doFilter(e) {
    if (!e) var e = window.event;
	if (e.target) var o = e.target;
	else if (e.srcElement) var o = e.srcElement;
	if (o.nodeType == 3) // defeat Safari bug
		o = o.parentNode;
    
    if (e.keyCode != 8) {
        var p = o.value;
        p = p.replace(/[^0-9]/g, "");
        
        if ( p.length >= 7 )
            o.value = p.substr( 0, 1 ) + " (" + p.substr(1, 3) + ") " + p.substr(4, 3) + "-" + p.substr(7, 4);
        else if ( p.length >= 4 )
            o.value = p.substr( 0, 1 ) + " (" + p.substr(1, 3) + ") " + p.substr(4, 3);
        else if ( p.length == 1 )
            o.value = p.substr( 0, 1 ) + " (";
    }
}
    
    //--></script>
</head>

<body>

<form>
    <label for="t1">
        Enter phone number including country and area code:
        <input name="t1" type="text" onkeyup="doFilter(event);" />
    </label>
</form>

</body>
</html>



*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
[banghead]
 
You beat me to it.
Here is what I came up with.
It allows backspace and removes 1 if it appears at the beginning of the string or in the first position of the prefix. I tested for operation in NS,FF and IE.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Phone number formatter</title>
<script type="text/javascript">
<!--
function doFilter(e,o) {
  var key = window.event ? e.keyCode : e.which;
  var p = o.value;
  if (key == 8)
    p = (p.length == 5)? p.substring(0,p.length-2) : (p.length == 9)? p.substring(0,p.length-1) : p;
  p = p.replace(/[^0-9]/g, "");
  for (var x=0;x<p.length;x++) { //Do not allow areacode to start with a 1.
    if (p.charAt(0) == 1)
      p = p.substring(1);
  }
  for (var x=0;x<p.length;x++) { //Do not allow local exchange to start with a 1.
    if (p.charAt(3) == 1)
      p = p.substring(0,3) + p.substring(4);
  }
  if ( p.length >= 6 )
    o.value = "(" + p.substr(0, 3) + ") " + p.substr(3, 3) + "-" + p.substr(6, 4);
  else if ( p.length >= 3 )
    o.value = "(" + p.substr(0, 3) + ") " + p.substr(3, 3);
  else
    o.value = p;
}
//-->
</script>
</head>
<body>
<form>
  <input type="text" value="" onkeyup="doFilter(event,this);" />
</form>
</body>
</html>

Stamp out, eliminate and abolish redundancy!
 
Oh, I see you integrated the countrycode.
I was actually looking to eliminate it for use within U.S. and Canadian pages.
I was also eliminating 1 from being the first digit of the area code and the exchange since those would be invalid numbers.
If a number is pasted into the field and the pasted value contains a 1 in one of those positions it gets removed then it tests to see if the new digit in that position is a 1, etc.



Stamp out, eliminate and abolish redundancy!
 
gotcha. i am unaware of any phone number "rules", other than the basic 11 digits (including country code), which is why i didn't include any additional validations. why don't they allow 1's as the first digit of the area code?

i suppose dialing 9-1-123-456-7890 from a hotel or business could prove problematic...



*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
[banghead]
 
At one point I knew why there were no phone numbers with area codes or exchanges beginning with a 1 but I do not remember now.
It is true though, at least in the U.S. so I used that as an extra bit of validation. It of course will not suffice for international phone numbers. But perhaps the function could be set to operate with parameters indicating regional rules.


Stamp out, eliminate and abolish redundancy!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top