belugasanity Posted December 31, 2014 Share Posted December 31, 2014 I'm trying to add an email validation into the code so that it pops up with a similar message as the others if you don't use the @ or .com in your email address and it just ignores it and keeps sending the email anyways no matter what i put into the email field. here is the php i have for it i'm sure it's something really simple but i am not as familiar with php as i would like to be... When i try and test this to make sure it works it only gives me the message that my email has been sent and i want it to not send if the email address doesn't have the @ sign or the .com or whatever kind of website it's from. I bolded the code that is not working the way i want it too. <?php if ($_POST['submit']) { if ($name != '' && $email != '') { if ($human == '4') { if (mail ($to, $subject, $body, $from)) { echo '<p>Your message has been sent!</p>'; } else { echo '<p>Something went wrong, go back and try again!</p>'; } } else if ($_POST['submit'] && $human != '4') { echo '<p>You answered the anti-spam question incorrectly!</p>'; } if (preg_match('/([\w\-]+\@[\w\-]+\.[\w\-]+)/', $email)) { echo '<p>Invalid email address</p>'; } } else { echo '<p>You need to fill in all required fields!!</p>'; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/293541-help-validating-email-address-in-form/ Share on other sites More sharing options...
requinix Posted December 31, 2014 Share Posted December 31, 2014 The code that does the email is near the top. You put the check near the bottom. It's not going to happen in time to do anything useful. The best thing you can do is restructure the code so that it's easier to work with. Do a series of checks for various types of errors and keep track of them as you go. If, after all the checks, there weren't any errors then you can send that email. It will also help cut down on how many levels of if blocks you nest together. if form was submitted { errors = array() if name or email is empty { add error message about filling in the required fields } if email is not empty and it does not match your regex { add error message about the invalid address } if they did not pass the captcha test { add error message about failing the captcha } if there were no errors { try to send the email. if successful { show the success message } else { show the failure message } } else { show the errors } } Quote Link to comment https://forums.phpfreaks.com/topic/293541-help-validating-email-address-in-form/#findComment-1501289 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.