Connecting Tech Pros Worldwide Forums | Help | Site Map

if statement

Familiar Sight
 
Join Date: Mar 2007
Posts: 146
#1: Jan 30 '09
I'm doing a form check and part of this is checking for mandatory fields. One field however is an email field that I'm checking for proper email structure ONLY if the field isn't left blank.

The code I'm using is turning an error message even if the email field is left blank.

Here's the original code:
Expand|Select|Wrap|Line Numbers
  1. if (eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['email']))))
  2. {
  3. $e = escape_data($_POST['email']);
  4. }
  5. else
  6. {
  7. $e = FALSE;
  8. echo "<tr><td align='left'><span style='font-size:14px; color:red; font-weight:bold;'>Please enter a valid email address.</span></td></tr>";
  9. }
And here's what I've tried but doesn't work:
Expand|Select|Wrap|Line Numbers
  1. if (!empty($_POST['email']))
  2. {
  3. if (eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['email']))))
  4. {
  5. $e = escape_data($_POST['email']);
  6. }
  7. else
  8. {
  9. $e = FALSE;
  10. echo "<tr><td align='left'><span style='font-size:14px; color:red; font-weight:bold;'>Please enter a valid email address.</span></td></tr>";
  11. }
  12. }
How can I write this code so that if the email field is empty it will just ignore the stupid thing and move on, and only perform the email structure check if something has been put into the email field?

Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,752
#2: Jan 30 '09

re: if statement


Hi.

Using the empty() and isset() functions should work.
It would be best to use trim() on the value tho, just in case.

Like:
Expand|Select|Wrap|Line Numbers
  1. if(isset($_POST['email']) && !empty(trim($_POST['email']))) {
  2.   // Do your validation here
  3. }
  4.  
If an empty "email" field is still being validated, there must be something else going on.
Reply