473,398 Members | 2,343 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Validating phone number

Hello,
I am very new to PHP, so I would greatly appreciate your help.
I am making a contact form with Name, Email and Phone text boxes. Validating email and name seems to be working fine, but phone number entry is not going so well. If I enter an invalid character (like a letter) or if I don't enter anything there, after I leave the text box, the error message is supposed to be shown above the phone number text box. And it is not happening. Please help me to find the error. Here is the PHP validation code I am using:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. // Clean up the input values
  4. foreach($_POST as $key => $value) {
  5.     if(ini_get('magic_quotes_gpc'))
  6.         $_POST[$key] = stripslashes($_POST[$key]);
  7.  
  8.     $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
  9. }
  10.  
  11. // Assign the input values to variables for easy reference
  12. $name = $_POST["name"];
  13. $email = $_POST["email"];
  14. $phone =$_POST ["phone"];
  15. $message = $_POST["message"];
  16.  
  17.  
  18. // Test input values for errors
  19. $errors = array();
  20. if(strlen($name) < 2) {
  21.     if(!$name) {
  22.         $errors[] = "You must enter a name.";
  23.     } else {
  24.         $errors[] = "Name must be at least 2 characters.";
  25.     }
  26. }
  27. if(!$email) {
  28.     $errors[] = "You must enter an email.";
  29. } else if(!validEmail($email)) {
  30.     $errors[] = "You must enter a valid email.";
  31. }
  32. //Errors here?
  33.  
  34. if(!$phone) {
  35.     $errors[] = "You must enter a phone number (000-000-0000).";
  36. } else if(!validPhone($phone)) {
  37.     $errors[] = "You must enter a valid phone number (000-000-0000).";
  38. }
  39. //end of errors here?
  40. if(strlen($message) < 10) {
  41.     if(!$message) {
  42.         $errors[] = "You must enter a message.";
  43.     } else {
  44.         $errors[] = "Message must be at least 10 characters.";
  45.     }
  46. }
  47.  
  48.  
  49. if($errors) {
  50.     // Output errors and die with a failure message
  51.     $errortext = "";
  52.     foreach($errors as $error) {
  53.         $errortext .= "<li>".$error."</li>";
  54.     }
  55.     die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
  56. }
  57.  
  58. // Send the email
  59. $to = "olga@dsign.pro";
  60. $subject = "Website Contact Form: $name";
  61. $message = "From: $name \r\nPhone: $phone \r\nMessage $message";
  62. //$message = "$message";
  63. $headers = "From: $email";
  64.  
  65. mail($to, $subject, $message, $headers);
  66.  
  67. // Die with a success message
  68. die("<span class='success'>Success! Your message has been sent. We will get back to you soon.</span>");
  69.  
  70. // A function that checks to see if
  71. // an email is valid
  72. function validEmail($email)
  73. {
  74.    $isValid = true;
  75.    $atIndex = strrpos($email, "@");
  76.    if (is_bool($atIndex) && !$atIndex)
  77.    {
  78.       $isValid = false;
  79.    }
  80.    else
  81.    {
  82.       $domain = substr($email, $atIndex+1);
  83.       $local = substr($email, 0, $atIndex);
  84.       $localLen = strlen($local);
  85.       $domainLen = strlen($domain);
  86.       if ($localLen < 1 || $localLen > 64)
  87.       {
  88.          // local part length exceeded
  89.          $isValid = false;
  90.       }
  91.       else if ($domainLen < 1 || $domainLen > 255)
  92.       {
  93.          // domain part length exceeded
  94.          $isValid = false;
  95.       }
  96.       else if ($local[0] == '.' || $local[$localLen-1] == '.')
  97.       {
  98.          // local part starts or ends with '.'
  99.          $isValid = false;
  100.       }
  101.       else if (preg_match('/\\.\\./', $local))
  102.       {
  103.          // local part has two consecutive dots
  104.          $isValid = false;
  105.       }
  106.       else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
  107.       {
  108.          // character not valid in domain part
  109.          $isValid = false;
  110.       }
  111.       else if (preg_match('/\\.\\./', $domain))
  112.       {
  113.          // domain part has two consecutive dots
  114.          $isValid = false;
  115.       }
  116.       else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
  117.                  str_replace("\\\\","",$local)))
  118.       {
  119.          // character not valid in local part unless 
  120.          // local part is quoted
  121.          if (!preg_match('/^"(\\\\"|[^"])+"$/',
  122.              str_replace("\\\\","",$local)))
  123.          {
  124.             $isValid = false;
  125.          }
  126.       }
  127.       if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
  128.       {
  129.          // domain not found in DNS
  130.          $isValid = false;
  131.       }
  132.    }
  133.    return $isValid;
  134. }
  135.  
  136. //function to check if phone # is valid 
  137. function validPhone($phone)
  138. {
  139.     $isValid = true;
  140.     if(!preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $phone))
  141.     {
  142.       // $phone is not valid
  143.           $isValid = false;
  144.      }
  145.  return $isValid;
  146. }
  147. // end of the function
  148. ?>
  149.  
The html form code is pretty basic:
Expand|Select|Wrap|Line Numbers
  1. <table><tbody><tr><td>
  2. <form id="contactform" action="processForm.php" method="post">
  3.                 <table>
  4.                     <tr>
  5.                         <td><label for="name">Name:</label></td>
  6.                         <td><input type="text" id="name" name="name" /></td>
  7.                     </tr>
  8.                     <tr>
  9.                         <td><label for="email">Email:</label></td>
  10.                         <td><input type="text" id="email" name="email" /></td>
  11.                     </tr>
  12.                     <tr>
  13.                         <td><label for="phone">Phone:</label></td>
  14.                         <td><input type="text" id="phone" name="phone" /></td>
  15.                     </tr>
  16.                     <tr>
  17.                         <td><label for="message">Message:</label></td>
  18.                         <td><textarea id="message" name="message" rows="5" cols="20"></textarea></td>
  19.                     </tr>
  20.                     <tr>
  21.                         <td></td>
  22.                         <td><input type="submit" value="Submit" id="send" /></td>
  23.                     </tr>
  24.                 </table>
  25.       </form>
  26.             <div id="response"></div>
  27. </td></tr></tbody></table>
Jul 1 '12 #1
1 3833
Atli
5,058 Expert 4TB
... after I leave the text box, the error message is supposed to be shown above the phone number text box.
Do you mean immediately after you leave the text box, before the form is submitted? If so, then that would be Javascript territory. You wouldn't find that error in your PHP code.
Jul 2 '12 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: joemono | last post by:
Hello everyone! First, I appologize if this posting isn't proper "netiquette" for this group. I've been working with perl for almost 2 years now. However, my regular expression knowledge is...
6
by: Poewood | last post by:
Is there a way to parse the contents of a textbox into a phone number format? Actually I would like to save the input as a number but display it as a phone number in the typical US format (000)...
1
by: Jeff Kiesel | last post by:
Has anyone used three textboxes for phone number input and successfully validated it? One textbox for area code, one for exchange, one for number. (yes, we're only doing US numbers) :o)
4
by: Brian Henry | last post by:
I have phone numbers like this in a data table 123-435-1234 1231231234 432.234.2321 they all have different formatting, what I want to do is get them all formatted like this (123) 123-1234
10
by: JackM | last post by:
I'm still working on validating the phone numbers that are entered on a form but have come across a problem I don't understand how to fix. I can handle most instances when it's in regular US...
3
by: venu | last post by:
Hi, I have a different requirement and it is : I need to validate a phone number field. It may or may not be a US phone number. The constraints are : *********************** # It should...
7
by: laredotornado | last post by:
Hi, Does anyone have a cross-browser JS function that validates a US phone number? I consider the following to be valid phone number formats: var p = "5558675309"; var p = "(312) 123-4567";...
2
by: komaladevi | last post by:
hello all ! Can any one help me in validating US Phone Number , I wrotethe javascript for this to get the phone number as 123-234-1234 but i dont know the reason why i am getting this format only...
5
by: Abhishek | last post by:
Hi this is my another validator in javascript to validate the Phone Number :-) <script language='javascript'> function funcCheckPhoneNumber(ctrtxtMobile,e){ if(window.event){ var strkeyIE =...
4
by: luke noob | last post by:
This is my HTML... <head> <script type="text/javascript" src="js/jquery-1.2.6.pack.js"></script> <script type="text/javascript" src="js/script.js"></script> </head> <body>
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.