0

Possible Duplicate:
How to validate an email address in PHP

Below I have a piece of code where it checks for a valid email address:

if ( (strlen($getemail) >= 7) && (strstr($getemail, "@")) && (strstr($getemail, ".")) ){

But what my question is that what is the opposite of the code above so that I can check if the email typed in does not contain all of the features above?

Community
  • 1
  • 1
user1881090
  • 739
  • 4
  • 16
  • 34
  • 1
    Could this be like .. a duplicate? –  Dec 10 '12 at 01:01
  • In any case, `!allOfFeatures` is the "opposite" of `allOfFeatures`; the boolean-logic negation can be applied through `&&` (and `||`) operators by De Morgan's, here are two answers I wrote on it in general: http://stackoverflow.com/questions/12169639/why-ssi-condition-doesnt-work?lq=1, http://stackoverflow.com/questions/6115801/how-do-i-test-if-a-variable-does-not-equal-either-of-two-values/6115869#6115869 (and they have sufficient detail for the "logic" of such inversions) –  Dec 10 '12 at 01:03

3 Answers3

3

PHP already has a function that can do this for you. It's called filter_var and what you're looking for is the validation filter for FILTER_VALIDATE_EMAIL.

Example:

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // It's a valid email address
} else {
    // It's not a valid email address
}
Sherif
  • 11,786
  • 3
  • 32
  • 57
2

It seems to me that what are you trying to do can be achieved be RegEx.

var_dump(preg_match('#^(\w+){7,}@(\w+)\.([a-z]){2,4}$#i', 'example@example.com')); # 1 (true)
var_dump(preg_match('#^(\w+){7,}@(\w+)\.([a-z]){2,4}$#i', 'foo@example.com')); # 0 (false)

If one of the conditions is not met (make sure address is alphanumeric, 7 chars minimum, followed by @, etc.), entire expression would result in false value.

Example:

if(preg_match('#^(\w+){7,}@(\w+)\.([a-z]){2,4}$#i', $email))
{
// do stuff
}

Do not validate email like that, use inbuilt filter_var function. There is no real way of validating if email is "real", main problem are domains, TLDs that is.

Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
0
if (!( (strlen($getemail) >= 7) && (strstr($getemail, "@")) && (strstr($getemail, ".")) )){
Mxyk
  • 10,678
  • 16
  • 57
  • 76
James McDonnell
  • 3,600
  • 1
  • 20
  • 26