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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Phone Number Validation 2

Status
Not open for further replies.

Tuck007

Technical User
Apr 29, 2002
105
US
In my form, I rquest the user to give his phone number in the form XXX-XXX-XXXX. I'm using split("-") to put the different parts of the phone number into an array. I'd like to just validate that a certain amount of characters are in each array. How can I do this?

Present Code:
Code:
<script LANGUAGE=&quot;JAVASCRIPT&quot;>

<!-- hide script from older bowsers

function validateForm(){

                 if ( window.document.frmSubmission.fname.value == &quot;&quot; ){
                         alert(&quot;Your first name is required.&quot;);
                        return false;
                 }
								 
                 if ( window.document.frmSubmission.phonenum.value == &quot;&quot; ){
                         alert(&quot;Your telephone number is required.&quot;);
                        return false;
								 }
								 
								 var phone_array = window.document.frmSubmission.phonenum.value.split(&quot;-&quot;);
								 
								 if ( phone_array[0] < 3 ){
								 		alert(&quot;Telephone number must be in this form: XXX-XXX-XXXX.&quot;);
										return false;
								 }
								 
								 if ( phone_array[1] < 3 ){
								 		alert(&quot;Telephone number must be in this form: XXX-XXX-XXXX.&quot;);
										return false;
								 }
								 
								 if ( phone_array[2] < 4 ){
								 		alert(&quot;Telephone number must be in this form: XXX-XXX-XXXX.&quot;);
										return false;
								 }
								 
								 if ( window.document.frmSubmission.email.value == &quot;&quot; ){
                         alert(&quot;Your email address is required.&quot;);
                        return false;
								 }
								 
								 var check_email = window.document.frmSubmission.email.value.indexOf(&quot;@&quot;);
								 
								 if (check_email == -1 ){
								 		alert(&quot;Please check your email address for proper format: yourname@yourprovider.com.&quot;);
										return false;
								 }
								 
								 if ( window.document.frmSubmission.street.value == &quot;&quot; ){
                         alert(&quot;Your full address is required.&quot;);
                        return false;
								 }
								 			
                 if ( window.document.frmSubmission.city.value == &quot;&quot; ){
                         alert(&quot;Your full address is required.&quot;);
                        return false;
								 }
								 
								 if ( window.document.frmSubmission.zip.value == &quot;&quot; ){
                         alert(&quot;Your full address is required.&quot;);
                        return false;
			
								 } else {
								 
                 return true;
								 
								 }
    }

//  end of code hiding -->
</script>

		<form ENCTYPE=&quot;multipart/form-data&quot; action=&quot;<?php echo $PHP_SELF; ?>&quot; method=&quot;post&quot; name=&quot;frmSubmission&quot; onSubmit=&quot;return validateForm()&quot;>

		<INPUT TYPE=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot; value=&quot;1048576&quot;>   

		<INPUT TYPE=&quot;hidden&quot; name=&quot;task&quot; value=&quot;upload&quot;>
		
					<table bgcolor=&quot;#eeeeee&quot; width=&quot;100%&quot; cellspacing=&quot;2&quot;>
		
					<tr>
					
					<td colspan=&quot;2&quot;>First Name*<br>
					
					<input type=&quot;text&quot; name=&quot;fname&quot;></td>
					
					</tr>
					<tr>
					
					<td colspan=&quot;2&quot;>Last Name<br>
					
					<input type=&quot;text&quot; name=&quot;lname&quot;></td>
					
					</tr>
					
					<tr>
					
					<td colspan=&quot;2&quot;>Telephone* (xxx-xxx-xxxx)<br>
					
					<input type=&quot;text&quot; name=&quot;phonenum&quot; maxlength=&quot;12&quot;></td>
					
					</tr>
					
					<tr>
					
					<td colspan=&quot;2&quot;>Email*<br>
					
					<input type=&quot;text&quot; name=&quot;email&quot;></td>
					
					</tr>
					
					<tr>
					
					<td colspan=&quot;2&quot;>Address*<br>
					
					<input size=&quot;35&quot; type=&quot;text&quot; name=&quot;street&quot;>
					
					</tr>
					
					<tr>
					
					<td colspan=&quot;2&quot;><select name=&quot;city&quot;>
					
					<?php
					//-- Select City
					include 'citylist.php';
					?>
					
					</select> CA     <input size=&quot;7&quot; name=&quot;zip&quot; type=&quot;text&quot; maxlength=&quot;5&quot;></td>
					
					</tr>
					
					<tr>
					
					<td colspan=&quot;2&quot;>Furnace Model<br>
					
					<input size=&quot;35&quot; type=&quot;text&quot; name=&quot;model&quot;>
					
					<tr>
					
					<tr>
					
					<td colspan=&quot;2&quot;>Photograph<br>
					
					<INPUT NAME=&quot;file&quot; TYPE=&quot;file&quot;>
					
					</td>
					
					</tr>
					
					<tr>
					
					<td colspan=&quot;2&quot;>Estimator<br>
					<select name=&quot;serviceman&quot;>
					<?php
					include 'estimator.php';
					?>
					<select>
					</td>
					
					</tr>
					
					<tr>
					
					<td align=&quot;center&quot; colspan=&quot;2&quot;><input type=&quot;submit&quot; name=&quot;Submit&quot; value=&quot;Submit&quot;>  <input type=&quot;reset&quot; name=&quot;Cancel&quot; value=&quot;Cancel&quot;></td>
					
					</tr>
					
					</table>
					
		</form> [B].:TUCK:.[/B]
 
I've had results using split that were inconsistent across browsers, especially if the split character was at the beginning or the end of the string (it is conceivable that a person would type &quot;-360-555-1212&quot;).

I split decimals of strings into sub-strings in the Multiply function of my code behind

Eventually, I discovered &quot;.search&quot; and afterwards only did those sorts of manipulation using .search, like so:
Code:
if (Divisor.search(/\./) == (-1))
  {
    // if it contains no decimal point, do...
  }
else
  {
    DivisorMultiplier = RegExp.leftContext
    // all the stuff to the left of the first
    // occurrence of the search term.
  }

Maybe that'll help.

Cheers,

Edward &quot;Do not read this sentence.&quot;
 
Like:
Code:
var phoneNmb = window.document.frmSubmission.phonenum.value

if( phoneNmbr.search(/\-/) == (-1)){
alert(&quot;Telephone number must be XXX-XXX-XXXX form.&quot;);
return false;
}

else{
var check_nums = RegExp.leftContext;
}

Ok, so how would I know that there are no more than 3 characters in check_nums? .:TUCK:.
 
Code:
if (check_nums.length == 3)
  {
    // everything's cool!
  }
else
  {
    alert(&quot;Please take your Parkinson's medicine and try again.&quot;);
  }

Keep in mind that &quot;.search&quot; only returns the first item it encounters. So, to verify that a phone number has been entered according to your specs, you'll probably search for parenthesis, dashes, etc.

The especially clever option is to take whatever they give you, strip everything out except [0..9] and reparse it yourself. Then present it to them on a verification form. That way, they can enter &quot;(206) 555-1212&quot;, &quot;206-555-1212&quot;, &quot;206.555.1212&quot;, &quot;2065551212&quot;, &quot;206 5551212&quot;, &quot;2a0b6c5d5e5f1g2h1i2j&quot; or whatever. Your code will eventually produce a verification screen with ALL their data, including &quot;Phone: (206) 555-1212&quot; and at the bottom, two buttons: &quot;Information Confirmed&quot; and &quot;Revise Information&quot;. The former button takes them on, and the latter button returns them to the data entry screen, but populating all the fields in advance with the formatted data that you presented in the Verification screen. As a &quot;hint&quot;, you might say. This lets them change only what they think is bogus, but not to have to reenter all that data again.

Good luck!

Edward &quot;Do not read this sentence.&quot;
 
how about this?
[tt]
function isPhoneNum(s) {
var pat = /^((\d\s?[\(\-\.\s]\s?)?\d{3}\s?[\)\-\.\s]?)?\s?\d{3}\s?[\.\-\s]?\s?\d{4}$/;
return pat.test(s);
}

var phoneNmb = window.document.frmSubmission.phonenum.value;
if (!isPhoneNum(phoneNmb))
alert(&quot;Telephone number must be XXX-XXX-XXXX form.&quot;);
[/tt]
=========================================================
if (!succeed) try();
-jeff
 
EdwardMartinIII,

This is how the whole process works, of course. I'm using PHP to handle the form itself and Javascript to validate that required information is entered. Since our customers could screw up on everything else very easily, I want the phone number to be exactly right. Our HVAC Estimators need to be able to call them and confirm info or make appointments. Therefore, it's wise to invest extra effort into checking that the phone number is area-pre-suffix 650-555-1212.
I would love to strip the value down to just the numerals, but I am still a newbie in javascript. I'll look into what I can do and of course, any suggestions are helpful. Thanks again to everyones help. .:TUCK:.
 
another way i've used is three separate text fields for area-pre-suffix. =========================================================
if (!succeed) try();
-jeff
 
Looking at both jemminger and EdwardMartinIII posts, I am trying this:
Code:
var phone_array = window.document.frmSubmission.phonenum.value.split(&quot;-&quot;);

if ( phone_array[0].length < 3 ){
alert(&quot;Telephone number must be in this form: XXX-XXX-XXXX.&quot;);
return false;
}
							
if ( phone_array[1].length < 3 ){
alert(&quot;Telephone number must be in this form: XXX-XXX-XXXX.&quot;);
return false;
}
if ( phone_array[2].length < 4 ){
alert(&quot;Telephone number must be in this form: XXX-XXX-XXXX.&quot;);
return false;
}

function isPhoneNum(s) {
	 var pat = /^((\d\s?[\(\-\.\s]\s?)?\d{3}\s?[\)\-\.\s]?)?\s?\d{3}\s?[\.\-\s]?\s?\d{4}$/;
	 return pat.test(s);
}

var phoneNmb = window.document.frmSubmission.phonenum.value;
if (!isPhoneNum(phoneNmb)) {
alert(&quot;Telephone number must be XXX-XXX-XXXX form.&quot;);
return false;
}

I see values to both suggestions and I'm hoping both work well. Thansk! .:TUCK:.
 
Tuck,

If you're using &quot;split&quot;, do try it under several different browsers, especially with &quot;206-555-1212-&quot; and &quot;-206-555-1212&quot;. Users put weird stuff in when they can and &quot;split&quot; behaves inconsistently when the split character is the first or last character.

Good luck!

Edward &quot;Do not read this sentence.&quot;
 
tuck,

be aware that my regex allows a variety of phone number formats, like:[tt]
1(800)555-5555
1 - 800 - 222 - 3333
333.3333
222.222.2222
1.234.567.8900[/tt]

optional acceptable delimiters are single whitespace, period, hyphen or parentheses

single whitespace before & after delimiters is also optional

the &quot;1&quot; in &quot;1 800 555 5555&quot; is optional

the area code is optional



if you want to explicitly allow xxx-xxx-xxxx ONLY, change &quot;pat&quot; to:[tt]
var pat = /^\d{3}-\d{3}-\d{4}$/;[/tt] =========================================================
if (!succeed) try();
-jeff
 
Tuck - if the phone number is that important, use three text fields. Your validation code will run faster and your customers will have an easier time correcting any errors.

One of the cardinal rules of programming is to keep it simple! There's always a better way...
 
Oh, of course. The simplest is to not make the User format anything. I wrote down an &quot;especially clever option&quot; earlier. No matter what the User types and however they format it, the code'll strip out everything but the numbers.

Then have the code reformat it (this basically takes no time). The only time you throw up an error is if the total number of digits is <> 10.

That way, formatting is completely irrelevant, but you end up with what you need.

Under no circumstances should the User be forced to make up for a lazy Programmer by formatting data that can just as easily be formatted by the code. 8)

Tuck, do you only expect US phone numbers? I ask because international phone number standardization is an art unto itself...

If you're sticking with US, then you can easily parseInt the text field, and check the .length against &quot;10&quot;. Then rebuild a new string: Number[0,1,2] + &quot;-&quot; + Number[3,4,5] + &quot;-&quot; + Number[6,7,8,9]. Um, that's pseudo-code, really, but the premise is the same.

Don't bug your User about formatting, just bug 'em if the number of digits is off.

Cheers,

Edward &quot;Do not read this sentence.&quot;
 
Hi Tuck,

This exact problem came up in one of our apps, so I had an opportunity to solve it.

Here are samples:

First, the HTML file, which you can save as whatever you like:

Code:
<!DOCTYPE html 
     PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
     &quot;[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;>[/URL]

<html xmlns=&quot;[URL unfurl="true"]http://www.w3.org/1999/xhtml&quot;[/URL] xml:lang=&quot;en&quot; lang=&quot;en&quot;>
  <head>
    <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot;></meta>
    <title>JavaScript Sample</title>
    <script src=&quot;Sample.js&quot; type=&quot;text/javascript&quot;></script>
  </head>
  <body>
    <form name=&quot;CustomerData&quot;>
      <input type=&quot;text&quot; id=&quot;PhoneNumber&quot;></input><input type=&quot;button&quot; value=&quot;Parse this US number&quot; onclick=&quot;CustomerData.PhoneNumber.value=ParseUSNumber(CustomerData.PhoneNumber.value)&quot;></input>
    </form>
  </body>
</html>

then the external JS file, which you should save as &quot;Sample.js&quot;:

Code:
function ParseUSNumber(PhoneNumberInitialString)
  {
    var FmtStr=&quot;&quot;;
    var index = 0;
    var LimitCheck;

    LimitCheck = PhoneNumberInitialString.length;
    while (index != LimitCheck)
      {
        if (isNaN(parseInt(PhoneNumberInitialString.charAt(index))))
          { }
        else
          { FmtStr = FmtStr + PhoneNumberInitialString.charAt(index); }
        index = index + 1;
      }
    if (FmtStr.length == 10)
      {
        FmtStr = &quot;(&quot; + FmtStr.substring(0,3) + &quot;) &quot; + FmtStr.substring(3,6) + &quot;-&quot; + FmtStr.substring(6,10);
      }
    else
      {
        FmtStr=PhoneNumberInitialString;
        alert(&quot;United States phone numbers must have exactly ten digits.&quot;);
      }
    return FmtStr;
  }

It looks really nice. It can probably be slimmed down with a regular expression, but at least this way, the logic's easier to follow.

This presupposes that the number WILL be a US number (and therefore must be 10 digits).

Also, the following rare type of string will be accepted and parsed as a phone number:
&quot;Bill watched 24 cows, 182 chickens, 28 pigs and 447 parakeets all get thrown into an industrial blender.&quot;

Weird, huh? Well, it's got ten digits... (72 parakeets and it would have triggered as an error)

I can't think of a really bulletproof way of avoiding that, given that a person might give us a numb in any sort of format, with spaces or whatever. At first, we sketched out a comparision of string sizes (if the incoming string were, oh, twenty or more characters, then chances were good it was some kind of leftover clipboard artifact), but the fact is, that doesn't help very much. After all, pasting &quot;fax: 555-555-1212&quot; into the &quot;home phone&quot; field isn't going to register using any of the filters, but would be very wrong.

So we settled on doing the autoformatting and letting the meat do its best at error catching.

Anyway, although I expect you've solved your problem by now, perhaps this might be something you can toss in for Phase II.

Cheers,

Edward &quot;Cut a hole in the door. Hang a flap. Criminy, why didn't I think of this earlier?!&quot; -- inventor of the cat door
 
Thanks! I'll return back to this when the time comes. You're right, it does look very neat. Thank you for all your help on this! .:TUCK:.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top