Example 140: Email Address Validation (PHP)

Description:   This example will demonstrate how to validate a properly constructed email address submitted from a form in a PHP program.
-This example uses regular expressions to do the validation.

Enter email Address:
example: excel@excelsystems.com

  1. Start with a "PHP Simple Page" template.


  2. Add the following HTML code after <div id="contents"> on the 'MainSeg' segment:
           <form name="val_email" action="validate_email.php" method="POST">
             <input type="hidden" name="task" value="val">
              <table>
                <tr>
                 <td>Enter email Address:<input type="text" name="email" size="30">
                 <input type="submit" value="Validate Email Address"></td>
                </tr>
               </table> 
              </form>
              
    <?php echo $msg; ?>
  3. In the PHP- Source Code create a global variable $msg.
    -This will be the message telling your users whether or not they entered a valid email address.

                global $msg;
                          


  4. In the PHP Source code, substitute this code:
       if ($pf_task == 'default')
    	   generic();
    	                    

    With this code:
       switch($pf_task)
       {
    	  case 'default':
    	  generic();
          break;
    	
    	  case 'val':
    	  validate();
    	  break;
        }
                            

  5. Create the validate function.
    Add this code under the generic function:
    function validate()
     {
      // Make all global variables available here
      foreach($GLOBALS as $arraykey=>$arrayvalue) 
    	{
    	 if($arraykey[0]!='_' && $arraykey != 'GLOBALS')
    	 global $$arraykey;
    	}
    
      $email = $_POST["email"];
      if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
       	$msg = "Please enter a valid email address";
      else
        $msg = "You have entered a valid email address";
        
      wrtseg('MainSeg');
    	
     }
                          
  6. Compile and run your progam.

Program Definition:   validate_email.pdw

Rate This Example

Did you find this example useful?  Yes  No  Don't Know

Enter additional comments below.   If you want to hear back from us, include your contact information.