Showing posts with label RegEx. Show all posts
Showing posts with label RegEx. Show all posts

Wednesday, July 31, 2013

Email Validation on PHP

I have made email validation before, but have forgotten where I placed that code.  I had to look for the RegEx (Regular Expression) around the net, there are some that work at a certain point, but does not if you had something like .com.ph or .com.us or .com.au.

There is also a question about the why the hyphen in his code does not work:
http://stackoverflow.com/questions/7939147/preg-match-email-validation-adding-hyphen-to-domain-spot

There is also this one that works, well almost (upper case letters not allowed on this one):
http://www.developphp.com/view_lesson.php?v=224

Explanations on how to add a hyphen to the Regular Expression:
http://stackoverflow.com/questions/9589074/regex-should-hyphens-be-escaped
http://stackoverflow.com/questions/6744587/simple-regex-match-any-string-with-at-least-one-hyphen


So I tweak  the code a bit to have the perfect email validation code I have seen so far, and here it is:

$email = "test@test-tester.com.ph" //<-- Works

$Syntax='/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$/';

if (preg_match($Syntax, $email)) {
     echo $email . \" is a valid email. We can accept it.\";
} else { 
     echo $email . \" is an invalid email. Please try again.\";
} 

Let me know if there is an improvement for this code.

Also a bit of caveat on the preg_match() function:
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred

as mentioned in PHP documentation: 

Wednesday, December 26, 2012

Free Mobile Browser Detection code generation

While searching for a mobile browser detection code, I came across this site: http://detectmobilebrowsers.com/

This site generates the code for popular browsers to detect using the USER AGENT of the browser used.  It's free to use, and donation to keep the site alive is pretty much appreciated by the author.

This is another useful website, that is simple to use, but takes a while to dissect the code. You pretty much need to brush up on your regular expression to understand the code and what it compares.  But if you are not worried about the code behind the detection, by all means, just paste the code to your site and set the redirection page.