1

Possible Duplicate:
PHP validation/regex for URL

I'm building a small app in PHP, and have to validate domain names (for use in E-mail addresses). For instance if I have mads@gmail.com I want to check if gmail.com is a valid domain name (I'm essentially throwing away the part before the @).

I have been using the following code:

if (!preg_match ("/^[a-z0-9][a-z0-9\-]+[a-z0-9](\.[a-z]{2,4})+$/i", trim($valid_emails[$i]))) {
         // Return error
}

And everything has been working fine. Until I got GE MoneyBank as a client. They are using ge.com as their domain, and that doesn't pass.

I have a rudimentary understanding of regex, and have tried deleting some of the [a-z0-9] blocks so the minimum character count comes down to 2, but without luck. Can anyone with more experience point me in the right direction?

Thanks in advance

Community
  • 1
  • 1
mads
  • 225
  • 1
  • 2
  • 8
  • 1
    It won't handle `.museum` TLDs either. – Quentin Dec 29 '10 at 00:27
  • dupe? http://stackoverflow.com/questions/156430/regexp-recognition-of-email-address-hard http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses – mth Dec 29 '10 at 00:28
  • @David Dorward, My answer should support all known TLDs. – Jacob Relkin Dec 29 '10 at 00:32
  • I don't think this is a duplicate at all - the other post states that the function is overkill and validates a whole URL, not just the domain and tld. for somebody who doesn't understand regular expressions, I think this could be helpful. – zsalzbank Dec 29 '10 at 19:10

1 Answers1

1

What you currently have does the following:
- [a-z0-9]: A letter or a number
- [a-z0-9\-]+: A letter or a number or a hyphen, 1 or more times
- [a-z0-9]: A letter or a number

Your problem is that it is expecting at least 3 letters.

You need to make sure it can accept only two letters, and the last one can't be a hyphen.

So you need to change the middle expression to 0 or more times:
- [a-z0-9\-]*: A letter or a number or a hyphen, 0 or more times

zsalzbank
  • 9,685
  • 1
  • 26
  • 39