Reputation: 6318
I am trying to validate an email field. I took this regex from somewhere on here for and I used it on another form I made and it works fine. Yet when I use it now its not matching.
All I am trying to do is to check the email and if it is good then log it in the proper field in the db.
For the sake of not pasting a bunch of stuff... I have stripped out the problem lines and going to pseudo code next few lines.
Essentially, vars are these:
$theEmail = $_post email from first page here
$regEx ='#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si';
and my php is this
//essentially other field validation will go here...for now testing only empty.
if(!empty($theEmail)){
if (preg_match($regEx, $formEmail)) {
//send it through to db.
} else { //error stuff here }
}
essentially, this never comes true. The email never validates no matter what I do and as I said I wrote another more complicated form that validates data just fine
Not sure what is going on.
Upvotes: 1
Views: 107
Reputation: 14681
I would suggest you to use filter_var
instead.
if (filter_var($theEmail, FILTER_VALIDATE_EMAIL)) {
//send it through to db.
} else {
//error stuff here
}
Upvotes: 4
Reputation:
give this a try! hopefully it will resolve your query, although there are infinte regulare expressions for email
^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$
For testing visit Regular Expression Tester
Upvotes: 0
Reputation: 2698
/^[a-z0-9.!\#$%&\'*+-=?^_{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$/
I removed the first #
and ending #si
, and took out the /
from the =
since it was giving me problems. This generates a match on my e-mail address here:
<?
$theEmail = '[email protected]';
$regEx ='/^[a-z0-9.!\#$%&\'*+-=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$/';
print_r(preg_match($regEx, $theEmail));
?>
Though this regex is very complex for something like e-mail validation- I would recommend trying to refine it and fine-tune it before putting it into production.
Upvotes: 0
Reputation: 354536
With email validation there are simple solutions that catch 99 % of all mistakes and complex solutions that might catch a tenth of a percent more, yet be unreadable.
Go the easy route and just check for something like
.+@.+\..+
Yes, it will allow an email address like [email protected]
but that's probably a smaller price to pay than a user who cannot register because your 500-character regex has a mistake in it somewhere, rejecting a valid address.
Upvotes: 0