Jump to content

Phone Validation on Multiple Phone Number Fields


bluebuffalo

Recommended Posts

Hi everyone,

 

I have an html form that gets processed by a "send.php" page.  As you can see by my code below, I have a few different requirements for fields that need to be filled out and/or validated.  I have been trying to add a simple phone validation.  I can do it for one phone field, but I have 3 phone fields.  I have a requirement to have at least one phone field required.  However, I have not been able to find code to have it validate a phone number(s), and have it work with the "at least one field required" requirement.

 

For example, if the user submits a home phone and a cell phone number, I need it to validate the format of the phone number (xxx-xxx-xxxx).  If they submit it wrong, have it say "try phone number again" - but if they are right, then have it continue processing the form.  Or, if they only submit the home phone, then only have it check that field, and not worry about the cell phone or work phone fields.

 

Or, should I just try some javascript on the html form?  Feel free to ask questions if I wasn't clear enough.  Thanks in advance for your help!

 

 

<?php
function check_email_address($email) {
  // First, we check that there's one @ symbol, and that the lengths are right
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
    return false;
  }
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
      return false;
    }
  }  
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}
$to       = "name@domain.com";
$country     = $_POST['country'];
$firstname     = $_POST['firstname'];
$lastname     = $_POST['lastname'];
$address     = $_POST['address'];
$aptsuite     = $_POST['aptsuite'];
$city     = $_POST['city'];
$state     = $_POST['state'];
$zipcode     = $_POST['zipcode'];
$email    = $_POST['email'];
$homephone     = $_POST['homephone'];
$workphone     = $_POST['workphone'];
$cellphone     = $_POST['cellphone'];
$sub      = "Information Request";
$headers  = "From: $email <$email>\n";  
$headers .= "Content-Type: text/plain; charset=iso-8859-1\n";
$mes     .= "Country: ".$country."\n";
$mes     .= "First Name: ".$firstname."\n" ;
$mes     .= "Last Name: ".$lastname."\n" ;
$mes     .= "Address: ".$address."\n";
$mes     .= "Apt/Suite: ".$aptsuite."\n";
$mes     .= "City: ".$city."\n";
$mes     .= "State: ".$state."\n";
$mes     .= "Zip Code: ".$zipcode."\n";
$mes     .= 'Email: '.$email."\n";
$mes     .= 'Home Phone: '.$homephone."\n";
$mes     .= 'Work Phone: '.$workphone."\n";
$mes     .= 'Cell Phone: '.$cellphone."\n";

if (empty($country) || empty($firstname) || empty($lastname) || empty($address) || empty($city) ||  empty($state) || empty($zipcode) || empty($email))
{
     echo "   <h3>Sorry, fields with an asterisk are required.</h3>";
}
elseif (empty($homephone) && empty($workphone) && empty($cellphone)) 
{ 
     echo "   <h3>At Least One Phone Number must be entered.</h3>";
} 
elseif (check_email_address($email)) 
{
mail($to, $sub, $mes, $headers);
echo "<meta http-equiv=\"refresh\" content=\"0;URL=thankyou.html\">";
} 
ELSE 
{
echo ("This email address is not valid.  Please go back and enter it again.");
} 
?>

 

Link to comment
Share on other sites

Javascript is usually better so they do not have to process twice. Ajax works nicely to for real-time updates.

 

If I were you I would do error checks with Javascript to avoid the annoying "crap now I gotta go back" issue.

Link to comment
Share on other sites

  • 2 years later...

Hi everyone,

 

I can do it for one phone field, but I have 3 phone fields.  I have a requirement to have at least one phone field required.  However, I have not been able to find code to have it validate a phone number(s), and have it work with the "at least one field required" requirement.

 

 

 

I know this is an old post... did you get an answer?

 

Your Question intrigues me as I am now working on a function the will validate phone numbers input from people in 172 countries!  Likewise I plan to ask Cell and Land Line and perhaps work phone info and require that one of those be complete!

 

Right now I am doing research on all the different syntax for phone numbers around the world. So before I reinvent the wheel on the 1 out of three phone number issue... Can you post whatever results you had?

 

Thanks...

 

Lan

 

PS to frost110

 

I have been working with PHP for more than ten years, beck when it was called "Personal Home Page Tools".  Frankly, I would never allow an...

annoying 'crap now I gotta go back' issue.

 

PHP has wonderful ways to verify information, and if in error, to bring the client back to exactly the place where the error is without reloading or going back to anything and also displaying exactly what the error is and what is should be... In different languages if needed!

 

I like java and I use it for a few things, but for security nothing you put on a clients computer will ever compare with the server side scripting of PHP.  Plus, personally, I have never seen a java form verification that could do anything that properly written PHP code could not do also.

Link to comment
Share on other sites

After 10 years you should know the difference between java and javascript and call each by its name. (Not trying to offend you, but they're quite different)

 

Javascript form validation is never supposed to replace PHP validation as it goes against the most basic rule "Never trust client side information". It's just there to prevent having to wait for a trip to the server and back... which will never be something PHP can do on its own, unless it becomes a clientside language somehow.

 

You may want to take a look at the way phone number validation is handled with drupal as the page states:

# Validation of phone numbers for : France, UK, Netherlands, Italy, Russia, Spain, Australia, Czech, Hungaria, Costa Rica, US and Canada

Should safe you at least some work.

Link to comment
Share on other sites

No offense taken Axeia,

 

In fact I agree with you!

 

As for my "java" post - gee, I think that was a javaSlip, or even a java spill!  All I can say is too many late nights == blame it on the Philippine Time Zone!

 

I need another cup of hot java juice!  That was a really a java beaner I pulled!

 

However, You made my point exactly...

"Never trust client side information".

 

The other point being that php validation does not have to press the back button! (see frost110 post above that recommends dumping PHP validation and just using JavaScript).

 

Javascript is usually better so they do not have to process twice. Ajax works nicely to for real-time updates.

 

If I were you I would do error checks with Javascript (ie. instead of PHP) to avoid the annoying "crap now I gotta go back" issue.

 

It's just there to prevent having to wait for a trip to the server and back...

 

I do agree with you there... Although even that point is going by the wayside as server speeds and Internet speeds increase. Yet, I often write the PHP form validation and when all is well I take the RegEx's from the PHP and do JavaScript to do the same thing.  The JavaScript pre-conditions the data and gives the client the feel of "speed" while the PHP locks up the security!

 

Now that we got all that straighten out... Thanks for the drupal downloads.  I have read a few of their RegEx's.  It is interesting to me that they are using a (444) 867-5309 x1234 format for the North American +! country code...  The International standards would make it...

+1 444 867 5309 and I am not sure what they would do with the extension... x1234.

 

I think I am going to have to go get another cup of Java (!Script) and think over what to do about extensions!

 

For the Record Axeia, I am a dinosaur on the Internet.  I haven't been programing for 10 years (Actually I have been doing it 37 years - back to the days of Fortran and Cobol and ARPANET and my late good friend Jon Postel (Mr. Internet!)).  I have just been doing PHP for 10 years!  :)

 

Thanks again for the drupal link, it has a lot of good information about the format of telephone numbers in Europe.

 

LAN - (hey, I didn't write that on my birth certificate when I was a day old!)  Maybe the Nurse had too much $Java = 'black coffee' ; back in the early 50's!

 

Link to comment
Share on other sites

why not name the phone fields " foneField[] " so an array is created when it gets sent to the server.... once, it gets sent to the server, you can iterate through the foneField array and see if any numbers are set, and try utilizing maybe the clients contry code as a place to start for phone validation... i donno...maybe? :-P

 

also jQuery makes selecting multiple fields and sending a request to a php script/page quite simple also....

 

Link to comment
Share on other sites

I cam across this page....

http://www.fonefinder.net/

 

maybe you can query their website for information or inquire about the way they handle phone number look ups... :-)

 

ps-also cam accross this page

http://www.numberingplans.com/?page=dialling&sub=areacodes

 

maybe you can scrape their site of the information and use it in to your advantage... they provide you the state's area code/starting digits and how many digits follow them....

 

cheers!

Link to comment
Share on other sites

 

No, I never figured this one out.  I just had to explain to my client that I wasn't able to code anything that complex.

 

Sorry, wish I could help.

Hi BlueBuffalo,

 

I am NOT an expert! I'm just playing with friends that "play nice" and are willing to work out a solution.  I have never failed to find a solution it if was possible (except how to code an "&" into a $_GET var in a URL!  Ha Ha!  :D

 

Anyway, I do think what you are asking can be done.

 

Since I posted, I wrote a script that validates phone numbers for a local Ad site (But & Sell on the Internet) here in the Philippines.

 

The normal here is to ask for Country Code, Area Code and Phone number as separate Input fields. Think of $fonCC $fonArea and $fonNum - and the same for cell and fax (or work or home). You could put it in an array if you prefer.

 

I validate and store each of these separately because I use them for different things (for example, a person in the +63 country is in the Philippines and I do not need to ask them what country is their address in!

 

My validation is simple, I get rid of everything but numbers and ltrim leading 0's and check the result length against what is acceptable! For example 1-2 letters for an area code, 3,4, or 5 numbers for an extended area code. 4-7 numbers for a phone number. All that means is that a Philippine area code / phone number needs to be 9 digits if it is anywhere except Manila (area code "2") and 8 digits if it is in Manila.

 

I end up with a 1-2 digit area code and a 7 digit phone number. (I deal with CC's separately).  Being from the "Land of the Free and the home of the Braves!" (At least my brother lives in Atlanta!) I recognized your xxx-xxx-xxxx pattern ASAP.  Being one of the guys who actually helped put that into Ma Bell and GTE back before computers ran telephones as an advantage!

 

Anyway if I were you...

 

<?php

$phone = array('1 - (0)(213)3701234 - Thats My Phone Number!', '','213-5555-1212');
//	$phone = array('', '','');
//	$phone = array('1<418>5555-1212', '','1(213-3722-1234');
//	$phone = array('', '4145552674','2142141212');
//	$phone = array('1(0)(213)3701234', '0(212)674-3331','214-214-1212');

// Print the Array Just to see what is there!
echo 'Our Array at the Beginning!<br /><pre>';
print_r($phone);
echo '</pre><br /><br />';

// Loop One - The Input Loop from the Form - you get an array called $phone...
for ($i = 0; $i <= 2; $i++) {

	// Strip everything but the numbers...
	$phone[$i] = preg_replace("![^0-9.]!", "", $phone[$i]);

	// Phone Numbers Do Not Start with a Zero or One!
	$phone[$i] = ltrim($phone[$i], "01");

	// Is our format valid? 10 Digits is great! Zero is empty!
	switch (true) {
		case ($phone[$i] == 0): $phone["test$i"] = 'empty'; break;
		case (strlen($phone[$i]) == 10): $phone["test$i"] = 'pass'; break;
		case (strlen($phone[$i]) > 0): $phone["test$i"] = 'wrong'; break;
		default: $phone["test$i"] = 'error - Note: If you ever get this, the world has ended and you are dead!'; 
	}	
}

// I have a friend, she calls me Neo, I call her Switch!

	switch (true) {
		case ($phone['test0'] == 'pass'):
		case ($phone['test1'] == 'pass'):
		case ($phone['test2'] == 'pass'): $phone['oneOf3phones'] = 'YES! This guy is a good guy!'; break;
		default: $phone['oneOf3phones'] = 'No! These Three Numbers are NOT GOOD!' ;
	}	
// And the Winner is:

// Print the Array Just to see what is there!
echo 'Our Array at the End of Loop ONE!<br /><pre>';
print_r($phone);
echo '</pre><br />';

//Loop 2 - Maybe an Output Loop fed from MySQL ~OR~ the continuation of Input to store numbers in the xxx-xxx-xxxx format in MySQL
// Loop 2 Can also be used for addiional validation...
for ($i = 0; $i <= 2; $i++) {
	if ($phone["test$i"] == 'pass') { // Comment this line if you want to break down nmbers that are empty, wrong or in error...
		$phone["fon$i"]['part1'] = substr($phone[$i],0,3);
		$phone["fon$i"]['part2'] = substr($phone[$i],3,3);
		$phone["fon$i"]['part3'] = substr($phone[$i],6,7);	

		//////////////////////////////////////////////////////////////////
		// Area Codes Do Not Start with a Zero or One!
		$phone["fon$i"]['part2'] = ltrim($phone["fon$i"]['part2'], "01");
		// You may also want to test for an area code like 555 that may be used to enter a common bogus phone number to defeat your test...

		// Is our Area Code Three Digits! Zero is empty!
		switch (true) {
			case ($phone["fon$i"]['part2'] == 0): $phone["test$i"] = 'empty'; break;
			case ($phone["fon$i"]['part2'] == 555): $phone["test$i"] = 'cheater'; break; // Needs more code because Cheaters still pass!
			case (strlen($phone["fon$i"]['part2']) == 3): $phone["Phone$i"] = implode('-',$phone["fon$i"]); break;
			case (strlen($phone["fon$i"]['part2']) > 0): $phone["test$i"] = 'wrong'; break;
			default: $phone["test$i"] = 'error - Note: If you ever get this, There is a Terminator at your door!'; 
		}	
	}
}

// Print the Array Just to see what is there!
echo 'Our Array at the End!<br /><pre>';
print_r($phone);
echo '</pre><br />';

?>

 

This code produces this kind of results...

<?php
$phone = array('1(0)(213)3701234', '0(212)674-3331','214-214-1212');
?>

Our Array at the Beginning!

Array
(
    [0] => 1(0)(213)3701234
    [1] => 0(212)674-3331
    [2] => 214-214-1212
)



Our Array at the End of Loop ONE!

Array
(
    [0] => 2133701234
    [1] => 2126743331
    [2] => 2142141212
    [test0] => pass
    [test1] => pass
    [test2] => pass
    [oneOf3phones] => YES! This guy is a good guy!
)


Our Array at the End!

Array
(
    [0] => 2133701234
    [1] => 2126743331
    [2] => 2142141212
    [test0] => pass
    [test1] => pass
    [test2] => pass
    [oneOf3phones] => YES! This guy is a good guy!
    [fon0] => Array
        (
            [part1] => 213
            [part2] => 370
            [part3] => 1234
        )

    [Phone0] => 213-370-1234
    [fon1] => Array
        (
            [part1] => 212
            [part2] => 674
            [part3] => 3331
        )

    [Phone1] => 212-674-3331
    [fon2] => Array
        (
            [part1] => 214
            [part2] => 214
            [part3] => 1212
        )

    [Phone2] => 214-214-1212
)

 

 

<?php
$phone = array('', '4145552674','2142141212');
?>

Our Array at the Beginning!

Array
(
    [0] => 
    [1] => 4145552674
    [2] => 2142141212
)



Our Array at the End of Loop ONE!

Array
(
    [0] => 
    [1] => 4145552674
    [2] => 2142141212
    [test0] => empty
    [test1] => pass
    [test2] => pass
    [oneOf3phones] => YES! This guy is a good guy!
)


Our Array at the End!

Array
(
    [0] => 
    [1] => 4145552674
    [2] => 2142141212
    [test0] => empty
    [test1] => cheater
    [test2] => pass
    [oneOf3phones] => YES! This guy is a good guy!
    [fon1] => Array
        (
            [part1] => 414
            [part2] => 555
            [part3] => 2674
        )

    [fon2] => Array
        (
            [part1] => 214
            [part2] => 214
            [part3] => 1212
        )

    [Phone2] => 214-214-1212
)

 

 

<?php
$phone = array('1<418>5555-1212', '','1(213-3722-1234');
?>

Our Array at the Beginning!

Array
(
    [0] => 1<418>5555-1212
    [1] => 
    [2] => 1(213-3722-1234
)



Our Array at the End of Loop ONE!

Array
(
    [0] => 41855551212
    [1] => 
    [2] => 21337221234
    [test0] => wrong
    [test1] => empty
    [test2] => wrong
    [oneOf3phones] => No! These Three Numbers are NOT GOOD!
)


Our Array at the End!

Array
(
    [0] => 41855551212
    [1] => 
    [2] => 21337221234
    [test0] => wrong
    [test1] => empty
    [test2] => wrong
    [oneOf3phones] => No! These Three Numbers are NOT GOOD!
)

 

<?php
$phone = array('', '','');
?>

Our Array at the Beginning!

Array
(
    [0] => 
    [1] => 
    [2] => 
)



Our Array at the End of Loop ONE!

Array
(
    [0] => 
    [1] => 
    [2] => 
    [test0] => empty
    [test1] => empty
    [test2] => empty
    [oneOf3phones] => No! These Three Numbers are NOT GOOD!
)


Our Array at the End!

Array
(
    [0] => 
    [1] => 
    [2] => 
    [test0] => empty
    [test1] => empty
    [test2] => empty
    [oneOf3phones] => No! These Three Numbers are NOT GOOD!
)

 

 

<?php
$phone = array('1 - (0)(213)3701234 - Thats My Phone Number!', '','213-5555-1212');
?>

Our Array at the Beginning!

Array
(
    [0] => 1 - (0)(213)3701234 - Thats My Phone Number!
    [1] => 
    [2] => 213-5555-1212
)



Our Array at the End of Loop ONE!

Array
(
    [0] => 2133701234
    [1] => 
    [2] => 21355551212
    [test0] => pass
    [test1] => empty
    [test2] => wrong
    [oneOf3phones] => YES! This guy is a good guy!
)


Our Array at the End!

Array
(
    [0] => 2133701234
    [1] => 
    [2] => 21355551212
    [test0] => pass
    [test1] => empty
    [test2] => wrong
    [oneOf3phones] => YES! This guy is a good guy!
    [fon0] => Array
        (
            [part1] => 213
            [part2] => 370
            [part3] => 1234
        )

    [Phone0] => 213-370-1234
)

 

Well, I am sure there will be suggestions for improvements but this will give you a start on how to code this...

 

DarkSuperHero -

 

Thanks for the Links - they help!

 

why not name the phone fields " foneField[] " so an array is created when it gets sent to the server....

 

also jQuery makes selecting multiple fields and sending a request to a php script/page quite simple also....

 

 

Can you post a little snippet of code so show what you mean?

 

Thanks,

 

Lan

 

PS: My wife beat you too it!  She suggested using the Country code to determine the area code and the phone size.

 

So far I am seeing certain patterns...  For example in Japan and the Philippines, the area codes get longer when the area gets smaller in size of people.  However, the telephone numbers also are getting smaller to serve the smaller number of people.  So if you have a two digit area code, you have a seven digit number.  Likewise a five digit area code will get you a four digit number.  In the Philippines, the numbers add up to nine digits!  In Japan they add up to 10 digits like in the USA. They just call them different names! Talaga! (Filipino for Really!)

 

 

 

 

Link to comment
Share on other sites

Hi BlueBuffalo,

 

I am NOT an expert! I'm just playing with friends that "play nice" and are willing to work out a solution.  I have never failed to find a solution it if was possible (except how to code an "&" into a $_GET var in a URL!  Ha Ha!  :D

 

Anyway, I do think what you are asking can be done...

 

Thank you, Lan.  I will give it a shot and play with it.

 

Take care,

BlueBuffalo

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.