2010-08-14 21:04
浏览 31


I have the following part of a validation script:

$invalidEmailError .= "<br/>&raquo;&nbsp;You did not enter a valid E-mail address";    
$match = "/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/";

That's the expression, here is the validation:

if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email

I think that's enough info, let me know if more is needed.

Basically, what happens is the message "You did not enter a valid E-mail address" gets echoed no matter what. Whether a correct email address or an incorrect email address is entered.

Does anyone have any idea or a clue as to why?

EDIT: I'm running this on localhost (using Apache), could that be the reason as to why the preg_match ain't working?

Thanks! Amit

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doutan1857
    doutan1857 2010-08-14 21:08

    Your regex only includes [A-Z], not [a-z]. Try

    $match = "/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i";

    to make the regex case-insensitive.

    You can test this live on http://regexpal.com.

    However, I'd advise you to try one of the expressions on the page mentioned by strager: http://fightingforalostcause.net/misc/2006/compare-email-regex.php. They have been perfected over time and will probably behave better. But Gmail users will be satisfied with yours, since they'll be able to use plus aliases which are rejected incorrectly by many validators.

    点赞 评论
  • doufei2328
    doufei2328 2010-08-14 21:10

    You can always try debugging your regex using a simpler tool (I'm quite fond of using Notepad++ for this purpose) and performing iterative tests - ie. making the expression more/less complicated and seeing if that fixes/breaks things.

    点赞 评论
  • dreamact3026
    dreamact3026 2010-08-14 21:14

    You likely got the regular expression you're using from regular-expressions.info. On that page, the author states (emphasis added):

    If you want to use the regular expression above, there's two things you need to understand. First, long regexes make it difficult to nicely format paragraphs. So I didn't include a-z in any of the three character classes. This regex is intended to be used with your regex engine's "case insensitive" option turned on. (You'd be surprised how many "bug" reports I get about that.) Second, the above regex is delimited with word boundaries, which makes it suitable for extracting email addresses from files or larger blocks of text. If you want to check whether the user typed in a valid email address, replace the word boundaries with start-of-string and end-of-string anchors, like this: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$.

    To solve this problem, add the i PCRE flag after your regular expression.

    点赞 评论