CakePHP – Email Validation

After working for about one year, the BHJS Alumni website phase 2 is completed. But after it is deployed in production server, i found that some email addresses are regarded as invalid email address. The email validation rule which i used is provided by CakePHP. Only email addresses ended with .com, .org etc… could pass the validation rule.

So i ask the Google teacher and luckily i am not the only one to come across this problem.

Email Validation in cakephp

What i can do is writing my own validation rule which can be doned by regular expression in the model.php. Again, Google is really helpful and there are many regular expressions for email validation. Finally, i pick the following one.

^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$

Reference: TIP: Simple Regular Expression for Email Validation

And so in the model.php, i replaced the email validation as follow.

var $validate = array(
	'id' => array('numeric'),
	/* CakePHP has problem on email validate. Reference: http://groups.google.com.tw/group/cake-php/browse_thread/thread/3d0a47d417f4b09f
	'email_address' => array('notempty', 'email' => array('rule' => array('email', true),'message' => 'Please supply a valid email address.')),
	*/
	// The following change is done for the above problem. Reference: http://gofedora.com/tip-simple-regular-expressi-email-validation/
	'email_address' => array('notempty', 'email' => array('rule' => '/^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$/','message' => 'Please supply a valid email address.'))
);

Done. =)

4 thoughts on “CakePHP – Email Validation”

  1. in my case I have left off the second parameter ‘deep’, then it worked 🙂
    ’email_address’ => array(‘notempty’, ’email’ => array(‘rule’ => array(’email’)) …

    $deep is per default “false”
    Cake API:
    function email($check, $deep = false, $regex = null)

    Like

  2. hi,
    I used this email validation ,but it will not work proprerly. That means, only cheks ‘notempty’ or not but not checks it is valid or not

    Like

    1. Do you mean the regular expression checking does not work?

      Actually this post is quite old and i wonder if the current CakePHP version already have a better solution. =P

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.