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. |
-
Start with a "PHP Simple Page" template.
-
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; ?>
-
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;
-
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;
}
-
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');
}
-
Compile and run your progam.
|