I'm creating a form in PHP that contains a field called email where the user needs to enter his/her email ID. In order to ensure that the mail ID entered is authentic in terms of sy开发者_开发知识库ntax (eg. username_123@domain.com
is valid) I need to append some kind of validation to it. I find the situation quite nebulous as I don't understand how to check if the mail ID entered contains an @
symbol etc. Kindly help. Thanks. :)
Best solution is to just do:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
...
}
and let PHP handle the heavy work for you. Otherwise, if you want to be strictly correct and use a regex directly yourself, you'll be stuck with this monstrosity:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
for strict RFC2822 compliance.
First you need to define valid e-mail.
There are different approaches to this depending on how important is this validation to you.
Some folks use crazy by-the-RFC regexps.
Another extreme is save anything user entered and later try sending confirmation e-mail to that address. No confirmation = bad e-mail.
You'll probably want something in between: make sure there's an @
in the middle, for example:
$email_arr = explode('@', $email);
if (sizeof($email_arr) !== 2 || $email_arr[0] == '' || $email_arr[1] == '')
... // definitely not valid
UPD: Marc B nailed it with filter_var($email, FILTER_VALIDATE_EMAIL)
That's probably the best way.
You can use regex to validate the format:
<?php
$email = "someone@example.com"; // or perhaps $_POST['email'];
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
echo "Valid email address.";
}
else {
echo "Invalid email address.";
}
?>
http://php.net/manual/en/function.eregi.php
From my own code:
if( !preg_match( "(^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$)i", $email))
echo "E-mail address invalid";
A very small number of legitimate addresses may fail, such as anything @example.info
, and any email address that uses unusual characters, but for the most part this works nicely.
精彩评论