Tel: 0151 223 0001

We believe in three things: users, users, users.

Validate an email address with a regex pattern

Validate an email address with a regex pattern - brought to you by sdesign1 - PHP specialists

This article will explain how to identify a valid email address that has been inputted on a php form. The form has been setup to send using the "Post" method and this snippet should be used to validate the input from the form.

When users post information to your site, whether it's using a contact form or even registering to your website, an email address is always asked for. Validating an email address that a user has entered has benefits as:

  • the user may have mistyped their email address
  • it prevents spammers from entering any values into the field - thus stops the form from being sent

In the following code, the email field is comes from a form that has used the "post" method. If the email is not identified as a valid address, then it will add the message to an array called $errors which is intialised on the first line.

$email = $_POST['email'];

if(!eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', $email)) {
echo "This is not a valid email address"; }
 
else {
           
$email = $_POST['email']; }

The code above simply checks whether the inputed data from $_POST['email'] matches the format of an email address, if it doesn't then it will display "This is not a valid email address" - if the email is a match, then it will store it as $email, and you can then proceed with your script.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Fill in the blank