-5

This is my code.

function emailField($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL);   
}

and

if(emailField($_POST['email'])=='')
  {
    echo "Invalid email";
  }
  else
  {
  echo "Valid";
  }

This allows all the special characters. I want to allow underscore, hyphen and dot only. How to avoid?

PNG
  • 287
  • 2
  • 6
  • 18
  • 5
    Why would you avoid valid emails? `filter_var` with `FILTER_VALIDATE_EMAIL` only validates *valid* emails. Restricting it further means disallowing *valid* emails. – h2ooooooo Aug 18 '14 at 07:16
  • 2
    This characters are perfectly valid in email addresses. – idmean Aug 18 '14 at 07:17
  • This will help you http://stackoverflow.com/questions/12026842/how-to-validate-an-email-address-in-php – skmail Aug 18 '14 at 07:23

2 Answers2

0

Use a RegEx like this:

/^[\w\.]+@/

Then you should also check if the domain really exists.

PHP:

$regex = "/^[\w\.]+@/";
$email = emailField($_POST['email']);

$domain = preg_replace($regex, '', $email); //get the domain of the email address by removing the local-part

//Using checkdnsrr we are checking if this domain is registred
if($email == '' && preg_match($regex, $email) && checkdnsrr($domain)){
  echo "Valid";
}

See also: http://php.net/manual/en/function.checkdnsrr.php

idmean
  • 14,540
  • 9
  • 54
  • 83
  • \w includes both underscore and digit characters so you can omit the \d and _ from the expression. Also the characters matched by \w can depend a little on locale. – Nick Rice Aug 18 '14 at 07:58
0

Use both complicated filter_var validation and simple preg_match validation.

function validate_email_popularly($email) {
    return
        filter_var($email, FILTER_VALIDATE_EMAIL)
        && preg_match('/\A[\w.-]*+@[\w.-]*+\z/', $email)
    ;
}

You should also use filter_input instead of $_POST. This function can filter unexpected Notice: Undefined index or Array into False.

$email = filter_input(INPUT_POST, 'email');
echo validate_email_popularly($email) ? 'Valid' : 'Invalid';
mpyw
  • 5,526
  • 4
  • 30
  • 36