开发者

PHP server-side validation regular expression match

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, h开发者_Python百科ere 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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜