Email validation in Php


Now a day email_id become compulsory for any type of registration. Here i will show you how to use email field in registration form and how to validate it for wrong entry of email.  Php has inbuilt function to validate the email.

html code (emailvalid.php)
<!DOCTYPE html>
<html>
<head><title>expertcodingmaster.com</title>
</head>
<body bgcolor="thistle">
<fieldset>
<legend><font color="cyan" size="5px">Email address and Validation</font></legend>
<form method="post" action="valid.php">
Enter your Email address :- <input type="email" name="email">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($msg))
{
echo "<script>alert('$msg')</script>";
echo "<font color=purple size=6px>" . $msg . "</font>";
}
?>
</fieldset>
</body>
</html>

php code (valid.php)
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$email = strtolower(check($_POST['email']));

if(empty($email))
{
$msg = "Please enter your email";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$msg = "please enter valid email address";
}
        else
        {
                $msg = "Your email_id is :- " . $email;
         }
}
function check($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

The function check( ) is define to restrict the user to enter special characters. It also restrict user to perform anti programming so that your website does't get hacked.

The function strtolower( ) is used to convert the string into lower case. You have seen many time that by mistake when you enter your email address in upper case it get auto converted into lower case. The function strtolower( ) is used behind that to convert the string to lower case. Only then your email get valid for your login or for any type of registration.

The FILTER_VALIDATE_EMAIL function is Php inbuilt function it validate the email parameters likes dot, @ sign and the complete structure of email. It monitor all the sign and letters present in the email are pleased at the right place or not.


No comments: