0

I have an input field to enter an email address as follows:

 <input type="email" name="email" id="email" title="E-mail(Format: email@example.com)">

I want to check the validity of this when user submits the email address. So i used this code:

 <?php
 $email =($_POST['email']);
 if(!filter_var($email, FILTER_VALIDATE_EMAIL))
 {
 echo "E-mail is not valid";
 }
else
{
 echo "E-mail is valid"; }? >

But although i enter an email as 'someone@example' this will print 'email is valid'. How can i validate the emails with 'someone@example.com' format? That means the format and the need of '@' and '.com' ?

Dakshila Kamalsooriya
  • 1,391
  • 4
  • 17
  • 36

2 Answers2

0

You will need to use an e-mail regular expressions and PHP function preg_match http://au1.php.net/preg_match.

John Arckai
  • 83
  • 10
0

I recommend using this function

public static function isEmail($value)
  {
    $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part
    $localPart = "(?:\"(?:[ !\\x23-\\x5B\\x5D-\\x7E]*|\\\\[ -~])+\"|$atom+(?:\\.$atom+)*)"; // quoted or unquoted
    $alpha = "a-z\x80-\xFF"; // superset of IDN
    $domain = "[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?"; // RFC 1034 one domain component
    $topDomain = "[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";
    return (bool) preg_match("(^$localPart@(?:$domain\\.)+$topDomain\\z)i", $value);
}

Its from Nette framework and its the best function for email validation ive ever seen.

https://github.com/nette/nette/blob/master/Nette/Utils/Validators.php