Jump to content

REGEX FOR EMAIL ADDRESS


hype_rain

Recommended Posts

Hi,

 

I looked at the other posts on this subject, but due to fact that I am new to this and it is difficult to determine if some of the solutions are on point with my issue and I don't want to start extracting pieces of code that "look like" they could be the answer (thereby confusing myself even further), I just thought I would keep it simple, show you guys what I got, tell you what I want, and listen and learn.

 

I want to code regular expressions for email addresses.

 

Here is what I am using for basic validation

 

$val = new Zend_Validate_EmailAddress();

if (!$val->isValid($_POST['email'])) {

  $errors['email'] = 'Use a valid email address';

}

 

I don't know if Zend qualifies as "third party", because I don't know if that refers to frameworks. If it belongs in another forum, please move it and I will get  the message and follow the thread (if any) accordingly.

 

Kindly,

 

Hype

 

Link to comment
Share on other sites

Zend_Validate_EmailAddress() is definately part of the Zend framework, so you posted this in the right place.  I don't know why you would consider this a regex question however, since this is a zend framework built-in that you don't need to understand to use.  I guess you're basically accepting that the people who coded it fully understand and have implemented the relative RFC's not to mention the active state of acceptable top level domains.  Since you're using the isValid() method, here's what the code actually is for that in the version of ZF I have local to me:

public function isValid($value)
    {
        if (!is_string($value)) {
            $this->_error(self::INVALID);
            return false;
        }

        $matches = array();
        $length  = true;
        $this->_setValue($value);

        // Split email address up and disallow '..'
        if ((strpos($value, '..') !== false) or
            (!preg_match('/^(.+)@([^@]+)$/', $value, $matches))) {
            $this->_error(self::INVALID_FORMAT);
            return false;
        }

        $this->_localPart = $matches[1];
        $this->_hostname  = $matches[2];

        if ((strlen($this->_localPart) > 64) || (strlen($this->_hostname) >
255)) {
            $length = false;
            $this->_error(self::LENGTH_EXCEEDED);
        }

        // Match hostname part
        if ($this->_options['domain']) {
            $hostname = $this->_validateHostnamePart();
        }

        $local = $this->_validateLocalPart();

        // If both parts valid, return true
        if ($local && $length) {
            if (($this->_options['domain'] && $hostname) ||
!$this->_options['domain']) {
                return true;
            }
        }

        return false;
    }
}
?> 

 

So hopefully you can see that isValid has options, and also calls some other methods that do checks.  The comments claim that the class is written to the rfc2822 standard, so you can always take a look at that if you really want to explore this further. 

 

The basic regex is pretty simple, but then it builds upon that initial check having split the email into 2 pieces using the regex:  '^(.+)@([^@]+)$'  If you use a regex reference you should be able to understand what that matches.  Whereever there is a () around a portion of the regex, that portion will be captured, so you should be able to see that this will do a basic split of the 'emailuser' @ 'myhost.com'.  It also insures that the email user portion is less than 63 characters.

 

This is the type of thing that a simple regex wouldn't necessarily do, although as you can see it's not rocket science, nor would it be impossible to enforce the size limitation in the regex. 

 

The real power of using a class is in all the optional checks that the class allows for, even going so far as to do an MX lookup if you want, to make sure that the email domain really exists.  In your code sample, that check would not be done by default, but it's possible to turn it on if it's really important not to have people attempting to register bogus email addresses using nonexistent domains.

 

Link to comment
Share on other sites

Hey Giz,

 

Thanks for the prompt reply. I have been trying to successfully add this to my validation code, but no success. I am going to take a couple more stabs at it, though. If I still don't have any progress I will let you know ( I am VERY sure it's something I'm doing or not doing).

 

I have some exposure to PHP, but am still kinda new. I took a 6 week class (a joke) in which the instructor's answer to most things was, "...who cares how it works? It just works..." (and the remarkable scholarship of the western world just rolls right on). My point is this: I want to master the language and copying things into my pages without a.) understanding what is going on b.) without trying it myself is (besides being plain lazy) not what gets really killer web applications built. I know that much, if nothing else.

 

So, again, thanks for getting me started. I will keep trying and come back with solid, intelligent questions.

 

Also, can you please comment on (or suggest) any books for learning php? Right now, I am using the [...] videos, along with a couple other books (I don't know if I can mention proprietary names in these posts--can I?).

 

Lemme kno.

 

Thanks!

 

Hype...

Link to comment
Share on other sites

Hey Gizmo,

 

Here is  my code into which I would like to place the code you gave me. I keep screwing it up. Can you tell me how to place properly?

 

 

$errors = array();if ($_POST) {  // run the validation script  require_once('library.php');  try {// main script goes here$val = new Zend_Validate_Regex('/^[a-z]+[-\'a-z ]+$/i');if (!$val->isValid($_POST['first_name'])) {  $errors['first_name'] = 'Required field, no numbers';}if (!$val->isValid($_POST['surname'])) {  $errors['surname'] = 'Required field, no numbers';}$val = new Zend_Validate();$length = new Zend_Validate_StringLength(6,15);$val->addValidator($length);$val->addValidator(new Zend_Validate_Alnum());if (!$val->isValid($_POST['username'])) {  $errors['username'] = 'Use 6-15 letters or numbers only';} else {  $sql = $dbRead->quoteInto('SELECT user_id FROM users WHERE username = ?', $_POST['username']);      $result = $dbRead->fetchAll($sql);  if ($result) {	$errors['username'] = $_POST['username'] . ' is already in use';  }}$length->setMin(;$val = new Zend_Validate();$val->addValidator($length);$val->addValidator(new Zend_Validate_Alnum());if (!$val->isValid($_POST['password'])) {  $errors['password'] = 'Use 8-15 letters or numbers only';}$val = new Zend_Validate_Identical($_POST['password']);if (!$val->isValid($_POST['conf_password'])) {  $errors['conf_password'] = "Passwords don't match";}$val = new Zend_Validate_EmailAddress();if (!$val->isValid($_POST['email'])) {  $errors['email'] = 'Use a valid email address';}if (!$errors) {	//insert the details into the database	$data = array('first_name'  => $_POST['first_name'],				  'family_name' => $_POST['surname'],				  'username'    => $_POST['username'],				  'password'    => sha1($_POST['password']));				  $dbWrite->insert('users', $data);				  header('Location: login.php');}  } catch (Exception $e) {echo $e->getMessage();  }}

 

 

Thanks!

 

Hype

Link to comment
Share on other sites

I don't see any obvious problems with your code.  A couple things I would do:

 

- at the top declare $errors so you don't get a php Notice.

 

$errors = array();

 

At the bottom check to see if errors actually contains anything:

 

if (count($errors) == 0) {

 

In your $data array you aren't actually using the $email address, so that looks suspicious to me. Not sure if that's an error or not, but I assume you want to actually add that to the insert.

 

 

Otherwise, the code looks solid and you have a good grasp on how to instantiate objects and call their methods.

Link to comment
Share on other sites

Hey Giz,

 

Also, can you please comment on (or suggest) any books for learning php? Right now, I am using the [...] videos, along with a couple other books (I don't know if I can mention proprietary names in these posts--can I?).

 

Lemme kno.

 

Thanks!

 

Hype...

 

Feel free to post about any resource you use, the only thing w frown upon is people attempting to use the forums for free advertising.  If you've used a video tutorial series and found it good or bad, that type of feedback is really useful for other people.

 

There is a sticky thread that has people's recommendations of books.  I learned the language a long time ago, and I don't have any particular recommendations, other than to say that the online manual is definitely worth going through, and is certainly what I go back to on a regular basis.

 

 

Link to comment
Share on other sites

I use the following:

 

<?php
class LibValidate {
    // ... snip

    /**
     * Returns true if the given text string matches the format for an e-mail
     * address.
     *
     * @param string $email
     * @return bool
     */
    public static function EmailFormat( $email ) {
        // Based on 'RFC Specification' @ http://en.wikipedia.org/wiki/E-mail_address
        $front = "([_A-Za-z0-9]|[!#\$%&'*+/=?`{|}~^-])+";
        $local = "({$front}([.]{$front})*){1,64}";

        $back = '[A-Za-z0-9-]+';
        $domain = "({$back}([.]{$back})+){1,255}";

        $regexp = "@^{$local}\\@{$domain}$@i";
        return preg_match( $regexp, $email ) ? true : false;
    }

}
?>

 

Invocation:

<?php
var_dump( LibValidate::EmailFormat( 'asdf@asdf.com' ) );
var_dump( LibValidate::EmailFormat( 'asdf..asdf@asdf.com' ) );
?> 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.