开发者

Invalid email address using preg_match [duplicate]

This question already开发者_如何学Python has answers here: Closed 11 years ago.

Possible Duplicate:

How to validate an email in php5?

I have used the following code to ensure email addresses provided on signup are valid.

(!preg_match("/^( [a-zA-Z0-9] )+( [a-zA-Z0-9\._-] )*@( [a-zA-Z0-9_-] )+( [a-zA-Z0-9\._-] +)+$/" , $email))

I entered a standard email address such as

yourname@company.co.uk

and it is flagging up as being invalid.

Can anyone help me with why this may be happening?


Why not just use filter_var

var_dump(filter_var($email,FILTER_VALIDATE_EMAIL));

EDIT

if(filter_var($email,FILTER_VALIDATE_EMAIL) === false)
{
   echo 'Email is not valid';
}
else
{
   //do the stuff
}


Now can I ask you a question? What are those spaces doing in your regular expression? :-)

I'm pretty certain that spaces aren't actually valid in email addresses. And, even if they were, they wouldn't be required to be at specific positions relative to the separators (such as immediately before and after the @ character).

Although I generally disagree with the use of regular expressions for email addresses (just send an email with a confirmation link - that solves your problem and then some a), you should at least use the right regular expression if you must do it that way.


a There are an untold number of perfectly valid email addresses that don't have an actual account behind them.


if you would like to use regex for matching emails, the following will match "sensible" addresses.

preg_match('/^([a-z0-9]+([_\.\-]{1}[a-z0-9]+)*){1}([@]){1}([a-z0-9]+([_\-]{1}[a-z0-9]+)*)+(([\.]{1}[a-z]{2,6}){0,3}){1}$/i', $email)

It's quite verbose but if you only want, like i said "sensible" addresses to pass - it does the job.

does get stuck on address like "example@somename.somewhere.com" because, after the @ symbol it looks for anything following a period to only be only 2-6 characters in length.

"example@somename-somewhere.com" however would pass fine.

I don't recommend trying to use a single regex solution for the job unless, as in my case, you only want to allow "sensible" addresses.

There is quite a good article that covers "correctly" validating email addresses here: http://www.linuxjournal.com/article/9585


With the new domainless addresses that are planned to be released, paxdiablo's solution seems even better

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜