Mann87
Mann87

Reputation: 324

Regexp valid email check

I try to check if an email is valid with the following regexp code.

/[0-9A-Za-z-_.]{1,64}[\@][0-9a-zA-Z\-]{1,63}[\.][a-zA-Z\-]{2,24}/

But in Tests I see that invalid emails like [email protected] or [email protected] or [email protected] or [email protected] or [email protected] or [email protected] are marked as valid.

I think in no valid email is . , _ , - on beginning or ending and not behind each other like -- or __ or -. or .- ...

What I could do to make it better?

Upvotes: 0

Views: 280

Answers (2)

Berlin
Berlin

Reputation: 1464

try this one:

^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$

another way:

^(|(([A-Za-z0-9]+)|([A-Za-z0-9]+)|([A-Za-z0-9]+(\.[_a-z0-9-]+)+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$

no match:

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

match:

[email protected]
[email protected]
[email protected]

Upvotes: 2

Louis Loudog Trottier
Louis Loudog Trottier

Reputation: 1377

Why not use http://php.net/manual/en/function.filter-var.php

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}

See filter definition here. http://php.net/manual/en/filter.filters.validate.php

Validates whether the value is a valid e-mail address.

In general, this validates e-mail addresses against the syntax in RFC 822, with the exceptions that comments and whitespace folding and dotless domain names are not supported.

Upvotes: 3

Related Questions