Latest update Email validation seems quite tricky. Do you have a better solution? Let’s have email validation challenge. And give the user the best way to validate an email format.
Mastering regex or regular expression is one advantages for you as programmer, but not everyone has time to learn something.
Not knowing how regex works doesn’t mean you couldn’t use the power of regex in your project.
Bookmark this list, so you can always going back here whenever you need this regex recipes.
Update :
Never though, my post will reach so many people, and cause so many reaction. But thank you to everyone, as I myself learn from my mistake.
Some credit goes to Joey Sochacki as I did use and modify some of his regular expression.
-
Validate email addresses
This is only basic email validation. Not recommended to use. Validate perfect email format using regex is not really efficient.
$email = "test@example.com"; if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email)) { echo "Your email is ok."; } else { echo "Wrong email address format"; }
A better solution for validate email syntax is using filter_var. Thanks to cx42net for pointing me out to filter_var.
if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) { echo "Your email is ok."; } else { echo "Wrong email address format."; }
-
Validate usernames
Validate username, consist of alpha-numeric (a-z, A-Z, 0-9), underscores, and has minimum 5 character and maximum 20 character. You could change the minimum character and maximum character to any number you like.
$username = "user_name12"; if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) { echo "Your username is ok."; } else { echo "Wrong username format."; }
-
Validate telephone numbers
Validate US phone number
$phone = "(021)423-2323"; if (preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phone)) { echo "Your phone number is ok."; } else { echo "Wrong phone number."; }
-
Validate IP addresses
$IP = "198.168.1.78"; if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)) { echo "Your IP address is ok."; } else { echo "Wrong IP address."; }
-
Validate postal codes
Validate US Postal codes
$zipcode = "12345-5434"; if (preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zipcode)) { echo "Your Zip code is ok."; } else { echo "Wrong Zip code."; }
-
Validate SSN
Validate US Sosial Security Number
$ssn = "333-23-2329"; if (preg_match('/^[\d]{3}-[\d]{2}-[\d]{4}$/',$ssn)) { echo "Your SSN is ok."; } else { echo "Wrong SSN."; }
-
Validate credit card
$cc = "378282246310005"; if (preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc)) { echo "Your credit card number is ok."; } else { echo "Wrong credit card number."; }
-
Validate domain
$url = "http://komunitasweb.com/"; if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) { echo "Your url is ok."; } else { echo "Wrong url."; }
-
Extract domain name from certain URL
$url = "http://komunitasweb.com/index.html"; preg_match('@^(?:http://)?([^/]+)@i', $url, $matches); $host = $matches[1]; echo $host;
-
Highlight a word in the content
$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor"; $text = preg_replace("/\b(regex)\b/i", '<span style="background:#5fc9f6">\1</span>', $text); echo $text;
Please note that some of this regex recipe doesn’t really validate to all conditions, therefore not a perfect solution, but it will cover most of the case. It’s not really worth to build perfect validation to all case, and waste your time in the process. Well that just my opinion. Feel free to share your regex magic and your opinion.
Related posts:
Some notice :
_ You should use some implemented tools like ctype and filter_var.
Filter_var will allow you to check many strings, like emails, urls, ips, types (int, array, etc).
_ The validator for the email address is wrong. In fact, according to the rfc, brackets are allowed too (“{“, “}”). But yes, I’d like to know someone that use these :p
_ For username, what about “Tom” ?
_ You should mention that the validator for phone numbers is for US format.
For example, a French version would be : 01 23 45 67 89
You also can put an internationnal version of your phone, and your validator wouldn’t work for this. (Using +33 1 23 45 67 89 OR 00 33 1 23 45 67 89 for an international french phone (+ or 00 are identical)).
@cx42net Thanks, I didn’t know about filter_var, and according to documentation it need PHP 5 >= 5.2.0. But filter_var make validation easier.
- I note that validator email not the perfect one. To tell you the truth I never see email with bracket. Even if you have one, I really doubt you can pass your email when you register with most of the site.
- For username validation, I use /i modifier, so it will be case-insensitive.
- Yap. It is US phone number.
Yes you right about emails with bracket, it’s just the rfc that tells that, but I’m sure all mail hosting won’t allow you to use some, so … :p
For username, I was thinking about a smaller size than 5. But after all, I think anyone that will use this regex will modify it according to his though. I don’t know how many users have a username with less than 5 chars …
it would be interesting to know that :)
Add additional information about username validation. Thanks to cx42net.
Nice stuff! If you can include them in a class it will be very good.
[...] the rest here: 10 Practical PHP Regular Expression Recipes | KomunitasWeb Tags: -htaccess-what, css, database, javascript, jquery, phone, project, recipe, recipes, regex, [...]
[...] komunitasweb Comparte esta [...]
[...] » 10 Practical PHP Regular Expression Recipes | KomunitasWeb [...]
Your first 8 examples claim to validate things, but validating data like e-mail addresses using regular expressions might not be the smartest thing to do. At most you can do a syntax check but validation…?
Checking e-mail addresses using regular expressions should result in either an insanely large regular expression (http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) or in a syntax check that only checks the basics (e.g. /^\S+\@\S+\.[a-z]{2,5}$/iD). But validating them would require a check with the smtp server.
The same goes for phonenumbers, the regular expression doesn’t check valid area codes so it simply check the syntax.
So these recipes are nice examples but using regular expressions should be a tool, not a goal.
@Takkie, I aware that this is not a perfect solution, especially for email. And yes, this is only validate syntax. Well just saying if you mean validate is real validation that you have to call each phone number to verify real phone number.
Most site will only validate basic email syntax, then they send verification through that email. If you try to register using weird email format, I believe it won’t pass the validation in most site.
The goal of validation process is to reduce errors as many as possible, not to eliminate the errors.
I agree regular expression is a tool not a goal. Knowing how to use and when to use regular expression is more powerful tool.
Hello,
Please add your site at http://www.sweebs.com. Sweebs.com is a place where other people can find you among the best sites on the internet!
Its just started and we are collecting the best found on the net! We will be delighted to have you in the sweebs listings.
Regards
Kris
Are you cleary sure that your regular expression for
“syntax-validating” of Email address NEVER reject
valid email address?
For example, foo+bar@gmail.com, it has a plus sign
in it, it’s valid and commonly used, but it seems
your regular expression says it’s “Wrong”
Your theory, real validation can be done only
through sending real email, sounds good, but
what if your script reject a valid email address,
then how can you go through registration process?
You must guarantee that your script never reject valid
addresses. (your script can say “It’s okay” for wrong
addresses, but your script must not say “It’s wrong” for
valid addresses)
I believe it’s better to edit your entry for correction,
not here as one of replies. If you leave your script
without correction, someday someone with a valid address will
surely encounter a trouble, because of you.
A bunch of those look strikingly similar to mine. :P Nice.
@J0hn D0e. I have add additional information to email validation. Thanks.
@Joey Sochacki. I did look to your post, and modify some of them. I have updated my post and give credit for you. Thanks
10 распространенных регулярных выражения для PHP…
Thank you for submitting this cool story – Trackback from progg.ru…
Good
Regarding phone number validation, please take a look at this post on my blog. It’s not ideal either, but I am looking to make it ideal one day. I need people’s comments and ideas for that though.
http://bit.ly/oyTgX
Thanks!
[...] Go here to read the rest: 10 Practical PHP Regular Expression Recipes | KomunitasWeb [...]
To extract domain name from URL use parse_url() function (http://www.php.net/parse_url
[...] 10 Practical PHP Regular Expression Recipes | KomunitasWeb [...]
[...] En este blog nos muestran 10 snippets para validación con PHP y Regexp. Hay validación de nombres, teléfonos, direcciones IP, dominios y tarjetas de crédito. Demo [...]
[...] 10 Practical PHP Regular Expression Recipes | KomunitasWeb [...]
[...] 10 Practical PHP Regular Expression Recipes [...]